Directory
1. # define defines constants, good and bad
2. Const keywords (various const objects, pointers, references, functions, and references)
Constant means that the value remains unchanged during running. The C language is defined by # define, a macro constant. Use # define and const to define constants in c ++.
Turn: http://blog.csdn.net/love_gaohz/article/details/7567856
Http://blog.sina.com.cn/s/blog_60be7ec80100gzhm.html
1. Define defines constants.
Defines global constants.
The define macro is expanded in the preprocessing phase.
No type, just expand, not expand Type
Just expand, where you can use it. (Macro definition does not allocate memory, variable definition needs to allocate memory)
Replacing strings is easy to produce unexpected errors (marginal benefits)
2. Const Constants
2.1 comparison of const and define
- Run and use in the compilation phase
- There are specific types. You need to check the types in the compilation phase.
- Const constants allocate memory in the memory, but only one allocation is performed.
- Integrated debugging tools can be used for debugging (this is unknown)
- You can define local constants or global constants (I think you can use static, which is to be learned later)
For others:
(1) Different define macros are processed by compilers in the preprocessing phase. Const constants are used in the compilation and running phase. (2) Different Types and security checks define macros have no types, and do not perform any type checks, just expand. Const constants have specific types. during compilation, the type check is performed. (3) Different Storage Methods define macros only expand. The memory will be expanded as many times as there are places to use and will not be allocated. (Macro definition does not allocate memory, variable definition allocates memory .) Const constants are allocated in memory (either in heap or stack ). (4) const can save space and avoid unnecessary memory allocation. For example: # define PI 3.14159 // constant macro const doulbe Pi = 3.14159; // pi is not put into ROM at this time ...... double I = PI; // at this time, the PI is allocated with memory and will not be allocated later! Double I = PI; // macro replacement during compilation, allocating Memory double J = PI; // no memory allocation double J = PI; // then macro replacement, allocate memory again! Const defines constants. From the assembly point of view, only the corresponding memory address is given, rather than the number of immediate values as # define. Therefore, the constant defined by const has only one copy during the program running (because it is a global read-only variable and has a static zone), and # The constant defined by define has several copies in the memory. (5) improved efficiency. Generally, the compiler does not allocate storage space for common const constants, but stores them in the symbol table, which makes it a constant during compilation without the operation of storage and read memory, this makes it highly efficient. (6) macro replacement is only used for replacement, without calculation or expression solving. Macro pre-compilation is used for replacement, and memory is not allocated when the program is running. Const and # define can be used to define constants in c ++, or # define can be used to define constants. However, the former has more advantages than the latter: (1) const constants have data types, while macro constants do not have data types. The compiler can perform type security checks on the former. However, only character replacement is performed for the latter, and there is no type security check. In addition, replacement may produce unexpected errors (marginal effect ). (2) Some integrated debugging tools can debug const constants, but cannot debug macro constants.
View code
2.2. Try to use const in C ++ to avoid using define.
Constants used externally should be placed in the header file, and internal constants should be placed in the header of the source file.
Constants can be defined in a file for ease of management.
2.3. Const member in the class
The space of a const-defined constant is released after function execution and object destruction.
For constants in a class that are only modified with const, they do not change with respect to objects, but change with respect to classes. Because a class can create many objects, initialization can be performed during constructor initialization.
Therefore, when the class declares a const member, the const constant cannot be assigned a value directly.
Class test {public: const int size = 10; // error, the const constant cannot be assigned an int array [size] in the class declaration; // The size is unknown.
}
In the class, how to assign values to const can only be assigned through the const initialization list, and must also be initialized in the initialization list. In this way, each object can have different const constants.
class Test{ public: const int size; Test(int s):size(s){ ... ... }};
So how can we achieve constant constants for the entire class? You can use enumeration and static Const.
Enumeration:
Class test {public: Test (): constvalue (9) {} Enum {size1 = 100, size2 = 200}; // enumeration PRIVATE: const int constvalue; // This is a const constant and can only be initialized in the constructor's initialization list. Static int staticvalue; // This is a static variable. The entire class can be used, and only one initialization can change the value of const static int allvalue; // static const is OK. this is a static constant}; int test: staticvalue = 10; // It cannot be initialized in the constructor initialization list or declaration, because it does not belong to a certain object const int test :: allvalue = 10; // when assigning values to static variables, do not add static values.
Summary: const member initialization:
- In a class, only const-modified constants can be initialized only in the initialization list of the const function. The constant values of the class corresponding to the const of each object can be different.
- In the class, const and static are modified in combination, and cannot be initialized in the constructor initialization list, because it does not belong to an object. To perform initialization outside the class, add const without static.
- In the function, the variable modified by const must be initialized at the time of declaration, and the variable will not be changed again.
- The const object is the local variable of the file by default.
2.4 const is the local variable of the file by default.
By default, const is the local variable of the file.
Defines non-const variables in the global scope, which can be accessed throughout the program.
// File_1.ccint counter; // defines // file_2.ccextern int counter; // counter ++ counter can be used through extern;
However, the const variable declared in the global scope is the local variable defined as the file. The file exists only in it and cannot be accessed by other files. If you want other files to be accessible, you must add extern to the front so that the const variable can be accessed throughout the program.
// File_1.cc // const must be initialized (function and global variable) when declared extern const int bufsize = FCN (); // file_2.ccextern const int bufsize; // you can use if (INT Index = 0; index! = Bufsize; ++ index )......
- This is because the non-const variable defaults to extern, but the const variable does not.
- If you want other const files to be accessible, specify the extern to be displayed. Of course, extern must be added to files used elsewhere. This is required for non-const and Const.
2.5 const reference
A reference is another name of an object. It performs various operations on the reference and operations on the original object. References are mainly used as row parameters of functions.
A reference is a composite type: A type defined by another type. That is, constants cannot be defined directly. Be sure to associate with other types.
References of the reference type cannot be defined, but any other types of references can be defined.
The reference must be initialized with another type. Must be initialized.
Once a reference is bound to an object, it cannot be bound to another object.
Int ivalue = 10;
Int & rvalue = ivalue; // This is the reference
A const reference is a reference to a const object.
- Since it is a reference to a const object, the const object cannot be changed, and its reference cannot be changed.
Therefore, the reference of the const object must meet the following requirements: 1. If the object is const, the reference is const.
Const int ival = 1024;
Const Int & rval = ival; // This reference is a reference pointing to the const object and cannot be changed. Because rval is associated with ival, ival cannot be changed, and rval cannot be changed, therefore, both must be const.
- The object can be not a const, but a reference can be a const.
Int I = 42;
Const Int & R = 42;
Const Int & r2 = R + I;
Or
Double dval = 3.14;
Const Int & rI = dval;
Because the compiler converts the code to the following form:
Int temp = dval;
Const Int & rI = temp;
The reference is bound to the RI. The change of dval does not affect the RI value.
Summary:
A non-const reference can only be bound to an object of the same type as the reference.
Values referenced by const can be bound to: 1. const of the same type, non-const object. 2. Const and non-const objects of the related type. 3. bind to the right value
Const references are used to avoid value assignment.
If the only purpose of referencing a row parameter is to avoid copying, it should be defined as Const.
2.6 const and pointer
This is complicated and hard to remember. There are two relationships between const and pointer: pointer to const object, const pointer
2.6.1 pointer to a const object
If the pointer is a const object, you cannot use the pointer to change the const value.
Const double * cptr; // pointer to the const object
Const limits the object referred to by the cptr pointer, not the cptr pointer. cptr does not have the const feature, so Initialization is not required during definition. Cptr can be re-assigned, that is, it can point to other objects. But it cannot be the same as what cptr points.
* Cptr = 42; // the content of the object to which the object is directed cannot be changed.
++ Cptr; // This is correct because the pointer does not have the const feature.
- Note: the address of a const object can only be assigned a pointer to a const object. If a pointer is assigned to a non-const object, an error occurs because the pointer can change the content.
Const double Pi = 3.14; double * PTR = & PI; // error. Use a pointer to a non-const object to point to the const object const double * cptr = & PI; // This is correct because the pointer to the const object points to the const object
You cannot use void * to save the const Object Pointer. You must use const void * to save the const object pointer.
- You can assign a non-const object address to the pointer to the const object.
double dval = 3.14;const double *cptr = &dval;
Although dval is not const, you cannot change the value of dval through cptr. You can change the value of dval in other ways.
Summary:
- The pointer to the const object cannot change the object to which it points anyway.
- A pointer to a const object can point to a const object or a non-const object.
- The pointer to the const object is often used as the row parameter of the function. Make sure that the actual object passed to the function is not damaged by the row parameter in the function.
- The base object cannot be changed, but the pointer can be changed. The pointer can point to multiple objects.
2.6.2 const pointer
Const pointer: the pointer cannot be changed, but the value of the object to which the Pointer Points can be changed. (if the object is not const, it can be changed. If it is const, it cannot be changed ). That is, this pointer can only point to one object. You can use this pointer to change the value of the object.
Int errnumb = 0;
Int * const curerr = & errnumb;
++ Curerr; // error because the pointer cannot be changed
* Curerr = 1; // pair
2.6.3 these two are hard to remember:
Ignore the type name first, and modify the name of the const if it is near it;
Const * P; // const modifier * p, p is the pointer, * P is the object pointed to by the pointer, immutable
* Const P; // const modifies P. P is immutable, and P points to a variable object.
Const * const P; // The first modifier * P, and the last modifier P
Summary:
- The pointer to the const object. The pointer is variable, and the object content is not variable. no matter whether the object is a const or not, the pointer cannot be used to modify the content of this object.
- Const pointer, the pointer is unchangeable, and the object can be determined based on the object type.
Note the following:
String S;
Typedef string * pstring;
Const pstring cstr1 = & S;
Pstring const cstr2 = & S;
String * const cstr3 = & S;
All three are the same. They are the const pointer to the string type object.
2.7 const parameter, Function
Const parameter: For a parameter that does not need to be changed in the function, it is better to define the parameter as const, because constants can be passed in.
Int strlen (const char * Str); // This can pass non-const string, const string, and "fjdajf" character constants. If no const exists, the string in the last condition cannot be passed. The first two methods validate the features that point to the const object.
Const function: defines a function as const, which is equivalent to modifying the return value and cannot be changed.
Int fun (void) const;
Const. If so, add more.
When writing this, I suddenly thought that the row parameter could be used as a topic: it involves the problem of referencing and passing arrays. There is also the volatile keyword.