Summary of C + + const usage

Source: Internet
Author: User

I. About General constantsthe format of the declaration or definition is as follows:Const < Type descriptor > < variable name > = < constant or constant expression >; [1]< type descriptor > Const < variable name > = < constant or constant expression >; [2]The definition of [1] and [2] is completely equivalent. For example:shaping Int (or other built-in type: Float,double,char)const int bufSize =;orint const BUFSIZE =;because constants cannot be modified after they are defined, they must be initialized when they are defined. bufSize = 128; Error:attempt to write to const objectConst string CNTSTR = "hello!";//Ok:initializedconst I, j = 0;//error:i is uninitialized constthe non-const variable defaults to extern. The Const object defaults to a local variable of the file. for a const variable to be accessible in another file, it must be explicitly specified as extern. For example:const int bufSize = 512; Scopes are limited to files that define this variableextern const int bufSize = full,//extern for widening scope, scope for entire source program (only if extern is outside the function can contain initialization) ii. about arrays and structuresthe format of the declaration or definition is as follows:Const < Type descriptor > < array name >[< size;] ... [1]< type descriptor > Const < array name >[< size;] ... [2]The definition of [1] and [2] is completely equivalent. For example:shaping Int (or other built-in type: Float,double,char)const int cntintarr[] = {1,2,3,4,5};orint const cntintarr[] = {1,2,3,4,5};struct SI{int i1;int i2;};const SI S[] = {{1,2},{3,4}};The two const above is a collection of variables that the compiler allocates memory for, so it cannot be used during compilation (for example:int temp[Cntintarr[2]], This way the compiler will report that a constant expression cannot be found) Iii. Referencesthe format of the declaration or definition is as follows:Const < Type descriptor > &< variable name > = ... [1]< type descriptor > Const &< variable name > = ... [2]The definition of [1] and [2] is completely equivalent. For example:const int i = n;const int &r = i; (or int const &R = i;)A const reference is a reference to a const object. A normal reference cannot be bound to a const object, but a const reference can be bound to a non-const object. const INT II = 456;int &rii = II;//Errorint JJ = 123;const int &RJJ = JJ;//OKa non-const reference can only be bound to an object of the same type as the reference. A const reference can be bound to an object of a different but related type, or to a right-hand value. For example:1.const int &r = 100; Binding to literal constants2.int i =;const int &R2 = R + i;//reference R bound to right value3.double dval = 3.1415;const int &ri = Dval; Integer reference bound to double typeThe compiler converts the above code into the following form of encoding:int temp = Dval; Create temporary int from doubleconst int &ri = temp;//bind RI to that temporary Iv. about Pointers 1. A pointer to a const object (the content pointed to by the pointer is a constant)the format of the declaration or definition is as follows (can not be initialized when defined):Const < Type descriptor > *< variable name > ... [1]< type descriptor > Const *< variable name > ... [2]The definition of [1] and [2] is completely equivalent. For example:const int i = +;const int *cptr = &i;orint const *CPTR = &i; [Cptr is a pointer to a const object of type int] allows the address of a non-const object to be assigned to a pointer to a const object , for example:double dval = 3.14; Dval is a double; Its value can is changeConst DOUBLE *CDPTR = &dVal;//ok;but can ' t change dval through CdptrYou cannot modify the underlying object with a pointer to a const object. However, if the pointer is pointing to a no-const object (such as Cdptr), you can modify the object it points to by using other methods. how can a const object be legitimately assigned to a normal pointer??? For example:Const Double dval = 3.14;double *ptr = &dVal;//ErrorDouble *ptr =const_cast<Double*> (&dval);//OK:Const_cast is a standard cast in C + + and uses the language: D ouble *ptr = (double*) &dval; 2.const Pointer (the pointer itself is a constant)the format of the declaration or definition is as follows (must be initialized when defined):< type descriptor > *const < variable name > = ...For example: int errnumb = 0;int ival = 10;int *const Curerr = &errNumb; [Curerr is a const pointer to an int type Object]The pointer cannot be modified. Curerr = &iVal;//error:curerr is constthe underlying object that the pointer points to can be modified. *curerr = 1;//Ok:reset value of the object (ERRNUMB) which Curerr is bind 3. A const pointer to a const object (both the pointer itself and the content pointed to are constants)The format of the declaration or definition is as follows (must be initialized when defined): Const < type descriptor > *const < variable name > = ...For example:const Double pi = 3.14159;Const Double dval = 3.14;Const double *const pi_ptr = &pi; [Pi_ptr is a const pointer to a const object of type double]The pointer cannot be modified. pi_ptr = &dVal;//error:pi_ptr is constthe underlying object that the pointer points to cannot be modified. *pi_ptr = dval;//ERROR:PI is const v. About general functions 1. Parameters of the modifier functionclass A;void func1 (const int i);//I cannot be modifiedvoid func3 (const A &ra); The object referenced by RA cannot be modified void Func2 (const char *PSTR);//The content pointed to by PSTR cannot be modified 2. The return value of the modifier functionreturn value: const int func1 (); Returns a const value of type int, meaning that the initial value of a variable in the returned original function cannot be modified, but the variable returned by the function is made into a copy, and can be modified without meaning. It can be assigned to any const or non- const type variable and does not need to be added to this const keyword at all. [* Note *] but this is only for the internal type (because the internal type is definitely a value returned, not a variable, not used as an lvalue, or the compiler will error), for the user-defined type, the return value is a constant is very important (later in the class will be discussed). return Reference: const int &FUNC2 (); Note Do not return a reference to a local object, otherwise a run-time error is reported: Because once the function is finished, the local object is disposed, and the function return value points to a memory space that is no longer valid for the program. return pointer: const int *FUNC3 ();//Note never return a pointer to a local object, because once the function ends, the local object is disposed, and the returned pointer becomes a dangling pointer to an object that no longer exists. Vi. about classclass A{Public :void func ();void func () const;Const a operator+ (const A &) const;Private:int num1;mutable int num2;const size_t size;}; 1. Modifying member Variablesconst size_t Size;//For const member variables, [1] must be initialized within the constructor, [2] can only be initialized by initializing the member list; [3] attempting to construct a const in the constructor body Initialization of member variables can cause compilation errors. For example:a::a (size_t sz): Size (SZ)//OK: Initialize the list of members with initialization{} a::a (size_t sz)
2. Modifier class member functionsvoid func () const;//const member functions are not allowed to modify data members, if modified, the compiler will error. If a member function does not need to modify a data member, it is best to declare it as a const member function, which greatly improves the robustness of the program. Const provides a reference for function overloadingclass A{Public :void func (); [1]: a functionvoid func () const;//[2]: Overload of previous function [1]......}; A A (ten); A.func (); Call function [1]const A B (+); B.func (); calling function [2]How do I modify a member variable in a const member function??? Here are a few ways ( only the first one is advocated , others are not recommended)(1) Standard way: mutableclass A{Public :a::a (int i): m_data (i) {}void SetValue (int i) {m_data = i;}Private:mutable int m_data;//Handle here};(2) Cast: Static_castclass A{Public :a::a (int i): m_data (i) {}void SetValue (int i){static_cast<int> (m_data) = i;}//Handled herePrivate:int m_data;};(3) Cast: Const_castclass A{Public :a::a (int i): m_data (i) {}void SetValue (int i){const_cast<a*> (this)->m_data = i;}//Handled herePrivate:int m_data;};(4) using the pointer: int *class A{Public :a::a (int i): m_data (i) {}void SetValue (int i){*m_data = i;}//Handled herePrivate:int *m_data;};(5) Undefined method of processingclass A{Public :a::a (int i): m_data (i) {}void SetValue (int i){int *p = (int*) &m_data; *p = i}//handling herePrivate:int m_data;};Note: Although this is said to be modifiable, the result is undefined, avoid use! 3. Modifying class Objectsconst a A;//class object A can only call the const member function, or the compiler will error. 4. Modifying the return value of a class member functionConst a operator+ (const A &) const; The previous const is used to modify the return value of the overloaded function operator+, which prevents the return value from being assigned as an lvalue. For example:A;A B;A C;A + b = C;//Errro: If there is no const-decorated return value, the compiler will not error. Vii. Some suggestions for using const

1. Bold use of the const, which will bring you endless benefits, but only if you have to understand the cause;2. To avoid the most general assignment error, such as the const variable assignment, the concrete visible study questions;3. Using const in parameters should use a reference or pointer instead of a generic object instance for the same reason;4.const in the member function of three kinds of usage (parameters, return values, functions) to be very good use;5. Do not easily set the return value type of the function as const;
6. In addition to overloading operators generally do not set the return value type as a const reference to an object; Viii. What are the main functions of cons?
1. You can define const constants and have immutability.
For example:const int max=100;
int Array[max];
2. Easy to type check, so that the compiler to deal with the content of more understanding, eliminate some hidden dangers. For example:void f (const int i) {...}
The compiler will know that I is a constant and does not allow modification;
3. Can avoid the ambiguity of the appearance of the figure, the same can be easily adjusted and modified parameters.
As with the definition of a macro, you can do it without changing it. As in (1), if you want to modify the content of Max, only need: const int max=you want;
4. Can protect the modified things, prevent accidental modification, enhance the robustness of the program.
Or the above example, if I is modified in the function body, the compiler will error;
For example:
void f (const int i) {i=10;//error!}
5. Provides a reference for function overloading.
Class A
{
......
void f (int i) {...} file:// aa function
void f (int i) const {...} file:// onoverloading of a function
......
};
6. You can save space and avoid unnecessary memory allocations.
For example:
#define PI 3.14159file://oftenVolume macro
Const DOULBE pi=3.14159; file://thisThe pi is not placed in ROM
......
Double I=pi; file://thisallocates memory for PI and is no longer assigned!
Double I=pi; file://Seriesmacro substitution during translation, allocating memory
Double J=pi; file://nothave memory allocations
Double J=pi; file://againmake a macro replacement and allocate memory again!
Const definition constants from the assembly point of view, just give the corresponding memory address, instead of the immediate number as given in # define, so the const definition of the constant in the program runs only one copy, and the constant defined by the # # has several copies in memory.
7. Improved efficiency.
The compiler typically does not allocate storage space for ordinary const constants, but instead saves them in the symbol table, which makes it a constant during compilation, without the storage and read memory operations, making it highly efficient. {    size = SZ;//Error: Attempting to initialize a const member variable in the constructor body}

Summary of C + + const usage

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.