[Basic-C + +-written assault] 5.C preprocessor, scope, static, const, memory management

Source: Internet
Author: User
Tags volatile

Overview:

The source code of the C preprocessor handler, which runs before the compiler, usually begins with the symbol #.

Also involves static, const knowledge points ... Some are similar to Java ... Some easily confuse t.t.

Many of the chapters in this chapter have not been contacted before and have been seen in the written test ... If there is any mistake, please correct me ~ ~

5.1 C Preprocessor

The preprocessing of C language has three main contents:

1) macro definition and macro substitution;

2) file contains;

3) conditional compilation.

The test site is relatively small, tell the corresponding need to pay attention to the place.

The essence of macro substitution is simple-- text substitution . About macro definitions and macro substitution notice the points:

1) macro names are generally capitalized, macro names and parameters can not have spaces between the parentheses, the macro definition at the end of the semicolon;

2) The macro substitution is replaced only, does not do the grammar examination, does not do the computation, does not do the expression solution;

3) macro substitution is done before compilation, memory is not allocated, function calls are run after the program is compiled, and memory is allocated;

4) function has only one return value, the use of macro can try to get multiple values;

5) macro substitution makes the source program grow longer and function calls do not;

6) macro substitution does not take up the elapsed time, only the compile time, function calls take up the elapsed time (allocation memory, retention field, value Pass, return value).

#inlcude接受两种形式的file contains :

1) <> form: Standard header file, the compiler looks for the header file in the location of the path's environment variable.

2) "" Form: Non-system files, usually found in the path where the source files are located.

5.2 Global variables and local variables

Global variable: Also known as an external variable, defined outside the function, which does not belong to a function, belongs to a source program file.

Knowledge point 1: a global variable that references another file without a file, either by referencing the header file or by using the extern keyword. There is a little difference, if the variable is written incorrectly, the way to refer to the header file during compilation will be error, with the extern keyword during compilation will not error, during the connection will be error.

Knowledge point 2: in a process-oriented language such as C, a local variable can have the same name as a global variable, and a local variable will mask the global variable.

Knowledge point 3: in the same file, when a local variable is shielded from a global variable and wants to use it, there are two ways of using the domain operator "::" and the other is to use "extern".

intCount =3;intMainvoid) {    intI, sum, Count =2;  for(i =0, sum =0; I < count; i+=2, count++) {        Static intCount =4; Count++; if(i%2==0) {            extern intcount; Count++; Sum+ = count;//Statement 1} sum+ = count;//Statement 2} printf ("%d%d", count, sum); return 0;}

In the above example, the output of two statements is 4 and 20, respectively.

It is necessary to distinguish the range of Count , for the For loop determines that the count,for loop inside the first row of main is the static COUNT,IF statement inside the external count, Statement 2 is the count of the first row in the for inside the static count,printf. Need to study carefully, you can change the code to see the output.

5.3 Static

There are three main functions of static without regard to classes:

1) If a global variable or function is preceded by a STATC, it will be hidden from other source files without worrying about naming conflicts.

2) uninitialized global static variables and local static variables are initialized to 0 by default.

3) Static can persist the contents of local variables.

the role of static in a class: represents an object belonging to a class other than this class (as in Java).

Static data members: visible to all instances, must be defined outside the body of the class definition.

Static member functions: You cannot access a fee-static data member that is part of a class object, and you cannot access a non-static member function (because an ordinary member function is always a specific object, it is generally implied that a this pointer points to the object itself and static members do not).

There are two points to note:

1) Static members can access each other; static member functions and static data members can be accessed arbitrarily by non-static member functions;

2) because there is no overhead for this pointer, the static member function has a slight increase in speed compared to the non-static member function of the class.

3) Static member functions cannot be declared as virtual functions, volatile.

class Base {    virtualstaticvoid dunc1 ();  // Error    Static void Const // Error    Static void volatile // Error }

5.4 Const

In C + +, the const qualifier converts an object to a constant.

Pointer to const: "CP is a pointer that points to a const double" so that what it points to cannot be changed.

Const double *CP;

Const pointer: "CP is a pointer, this pointer to a double const pointer", itself cannot be changed, but the point of the value can be changed.

Double 1.0 ; Double const CP = &d;

The most powerful usage of the const is the application that faces the function declaration. within a function declaration, a const can be associated with a function return value, each parameter, the function itself (if it is a member function).

Const-Decorated return value: Because the function cannot return a pointer to a local stack variable, the stack is cleaned up after the function returns, but it can return pointers to the allocated storage space in the heap or pointers to the static store, which are still valid after the function returns.

Parameters of the const modifier function: If it is a pass-through address, we should modify it as const as possible, and if not, make the pointer to const not be an argument. Such as:

int Fun (int * i);   // Compile Error "Const *int type is not compatible with formal parameters of int* type" Const int 1;  // should be changed to int fun (const int. *i)Fun (&a);

The application of Const in class

Const member functions:

class Base {    void  func1 ();     void Const ;};

In the code above, the function Func2 is a constant member function of class base, and the const declared at the end of the fun2 () function changes the type of the implied this parameter so that the object to which the this parameter points is a const type (this itself is of type base* const, After a const is declared at the end of the function, the type of this is const base* const, which is the object to which this pointer is also const). The const member function cannot modify the object that called the function (except for the mutable member).

The purpose of a const implementation of a member function is to ensure that the member function can be used on the const object itself. A const object, a pointer to a const object, or a reference can only call its const member function, which is an error if you try to invoke a non-const member function with them. Instead of a const object, you can call a non-const member function with a const member function. Obviously, if there is no const member function, then the operation of the const object is extremely difficult to invoke any member function, implement the const member function, so that the const object can be generated operations.

Const data member: must be initialized in the constructor's member initialization list.

struct Thing {    Thing (): Valueb (1) {...}  // must be  added    int Valuea;     Const int Valueb;}; Thing T;

initialization Issues for static, const, static const member variables:

1) Static statically member variables cannot be initialized inside a class, and within the class's internal knowledge declaration, the definition must be outside the body of the class definition.

2) const member variables cannot be initialized at the class definition, only through constructor initialization lists, and must have constructors.

3) const data members are constants only during the lifetime of an object, but are mutable for the entire class because the class can create multiple objects, and the values of the const members of different objects can be different.

4) To establish constants that are constant throughout the class, you should use the enumeration constants in the class to implement or use the static const. The following example:

classTest { Public: Test (): A (0) {}        enum{size1 = -, Size2 = $}; Private:        Const intA://can only be initialized in the constructor initialization list        Static intb//defined and initialized in the implementation file of the class        Const Static intC://c is an integer that can be initialized here and still needs to be defined outside the class definition body//if C is a non-integral type, it cannot be initialized here};intTest:: b =0;Const intTest:: c =0;//when assigning a value to a const static member variable, you do not need to add static, you must have a const

5.5 Memory management and release

A C + + program, the user's memory is mainly divided into the following parts: Stack, heap, static storage, literal constant area, code area.

5.5.1 C Memory Operation

The C language allocates and frees storage space with malloc and free.

voidGetMemory (Char*p) {p= (Char*)malloc( One);}intMainvoid) {    Char*str ="Hello"; GetMemory (str); strcpy (str,"Hello World"); printf ("%s", str); return 0;}

The appeal code is problematic, and at the beginning Str is a pointer to the literal constant area, and getmemory (str) does not allocate space for the new Str.

When the function calls the parameter, the STR and the parameter p, although pointing to the same, but their own address is different, is two different variables:

P points to a different position after malloc is executed, and then is released because P is a local variable (but malloc has no free space to be used).

STR has always been pointing to "Hello", that is, str points to the literal constant area, and the literal constant area is not allowed to modify, so call strcpy error.

5.5.2 C + + memory management

C + + uses new and delete implementations to allocate and free storage space.

1) Initialization of dynamically created objects

Typically, dynamically created objects are initialized with the class's default constructor for objects of class type if they do not provide display initialization, while objects of built-in types are not initialized. Such as:

string New string // invoking the default constructor initialization int New int ; // No initialization

Similarly, it is possible to display initialization of dynamically created objects.

string New string ();  // invoking the default constructor initialization int New int ();  // pi points to an int initialized to 0

It can be seen that for class types that provide a default constructor (such as String), it is not necessary to display initialization of their objects: whether the program is explicitly uninitialized or requires initialization, its default constructor is automatically called to initialize the object. For built-in types or types that do not have a default constructor defined, there are significant differences between the different initialization methods:

int New int;  // No initialization int New int // initialized to 0

When a dynamically created object is exhausted, the programmer must display the memory occupied by the object to free storage.

Use delete[] When reclaiming the memory space of a single object allocated with new and using Delete to reclaim the memory space of a set of objects allocated with new[].

2) Dynamic allocation and recycling of const objects

To create a const object dynamically:

Const int New Const int (1024x768);  // A pointer to the const int object must be initialized at creation time Const string New Const string;  // implicitly initialized, calling its constructor

To delete a const object:

Although a program cannot change the value of a const object, you can delete the object itself, as is the case with other dynamic objects, and the const dynamic object is freed with a delete pointer:

Delete // even a pointer to a const int object can effectively reclaim what PCI points to

Finally, a 2012 written question of Baidu:

the difference between Malloc/free and New/delete :

1) malloc and free are standard library functions for C/s + +, and New/delete is a C + + operator;

2) New automatically calculates the space that needs to be allocated, whereas malloc needs to manually calculate the number of bytes;

3) New is type-safe, and malloc is not, for example:

int New float [2//  compile time indicates error int* p = (int*)malloc(2*sizeof (double//  Compile-time cannot indicate error

4) New Call operator new allocates enough space and calls the constructor of the related object, and malloc cannot call the constructor; Delete invokes the destructor for the instance and then calls the class's operator delete to free up the space occupied by that memory instance. and free cannot call destructors;

5) Malloc/free needs the library file to indicate that New/delete is not required.

In general this part is written so much, the actual written question will also examine a piece of code, to find out the size of the memory leak, need to clear the situation and scope of action, this piece of understanding is not very deep, if there is not clear or wrong place, welcome to explore ~ ~ ~ Hope we all have a harvest ~ ~ 0.0

Back to the directory-C + + Basics-Written Assault overview

[Basic-C + +-written assault] 5.C preprocessor, scope, static, const, memory management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.