C + + Beginner Const usage Explained

Source: Internet
Author: User

About the in C + + Const OFFThe use of the key word is very flexible, and using the const will greatly improve the robustness of the program, referring to the Kang Jiandong's const use of a detailed article, some of which have been supplemented, wrote this article.

1. Const constants

Such as:

    1. const int max = 100;

Pros: Const constants have data types, and macro constants do not have data types. The compiler can perform type safety checks on the former, but only character substitution, no type safety checks, and unexpected errors in character substitution (marginal effect)

2. Const modifies the data member of the class.

Such as:

    1. Class A
    2. {
    3. const int size;
    4. ...
    5. }

Const data members are constants only for the lifetime of an object, but are mutable for the entire class. Because a class can create multiple objects, different objects can have different values for their const data members. You cannot initialize a const data member in a class declaration, because the compiler does not know what the value of the Const data member is when the object of the class is not created. Such as

    1. Class A
    2. {
    3. const int size = 100; Error
    4. int array[size]; Error, Unknown size
    5. }

The initialization of a const data member can only be done in the initialization table of the class's constructor. To build constants that are constant throughout the class, you should use the enumeration constants in the class to implement them. Such as

    1. Class A
    2. {...
    3. enum {size1=100, size2 = 200};
    4. int ARRAY1[SIZE1];
    5. int array2[size2];
    6. }

Enumeration constants do not consume objects ' storage space, they are evaluated all at compile time. However, the implied data type of an enumeration constant is an integer with a limited maximum value and cannot represent a floating-point number.

3. The case of the const modifier pointer

See the following formula:

    1. int b = 500;
    2. Const int* A = & [1]
    3. int const *A = & [2]
    4. int* const A = & [3]
    5. Const int* Const A = & [4]

If you can distinguish between the above four situations, then, congratulations, you have taken a welcome step. I don't know, it doesn't matter, we can refer to the practice on effective C + + ITEM21, if the const is on the left side of the asterisk, the const is used to decorate the variable pointed to by the pointer, that is, the pointer is constant, if the const is on the right side of the asterisk, A const is a modifier of the pointer itself, i.e. the pointer itself is a constant.

Thus, [1] and [2] are the same, all pointers to the content is constant (const placed in the position of the variable declarator independent), in this case, the content is not allowed to change operations, such as *a = 3; [3] for the pointer itself is a constant, and the pointer to the content is not a constant, In this case, you cannot make a change to the pointer itself, such as a++ is wrong; [4] is a constant for both the pointer itself and the pointed content.

4. The initialization of the const

Let's take a look at the const variable initialization.

1) Non-pointer const constant initialization:

    1. A b;
    2. Const A = b;

2) The case where the pointer const constant is initialized:

    1. A * d = new A ();
    2. CONST * C = D;
    3. Or:
    4. CONST * c = new A ();

3) reference to const constant initialization:

    1. A F;
    2. Const a& e = f; To do so, E can only access functions declared as const, and cannot access the general member functions;

[Think 1]: Is this the correct method for assigning the following values?

    1. Const * C=new A ();
    2. A * e = C;

[Think 2]: Is this the correct method for assigning the following values?

    1. A * Const C = new A ();
    2. A * b = c;

5. Another powerful feature of the const is its application in function declarations.

In a function declaration, a const can modify the return value of a function, or a parameter, and for a member function, it can be decorated as an entire function. There are a few situations where the following is a gradual explanation of usage:

    1. a& operator= (const a& A);
    2. void Fun0 (const A * A);
    3. void fun1 () const; FUN1 () is a class member function
    4. Const A FUN2 ();

1) const of modifier parameters

Such as:

    1. void Fun0 (const A * A);
    2. void fun1 (const a& A);

When the function is called, the const constant is initialized with the corresponding variable, and in the function body, the part that is modified by the const is often quantified, such as the parameter is a const * A, the contents of the pointer passed in can not be changed, and the content pointed to by the original pointer is protected, if the parameter is const A & A, you cannot change the referenced object that is passed in, protecting the properties of the original object.

[Note]: The parameter const is commonly used in cases where the parameter is a pointer or reference, and only the input parameters can be modified, if the input parameter is in the "value Pass" method, since the function will automatically generate a temporary variable for copying the parameter, the parameter does not need to be protected, so the const adornment is not required.

[summary] For input parameters of non-intrinsic data types, the "value passing" method is changed to "const reference passing", in order to improve efficiency. For example

Will

    1. void Func (a a);

Switch

    1. void Func (const A &a);

For input parameters of an internal data type, do not change the "value passing" method to "Const reference pass". Otherwise, it can not achieve the purpose of improving efficiency, but also reduces the comprehensible function. For example

    1. void Func (int x);

Should not be changed to

    1. void Func (const int &x);

2) const of the modified return value

Such as:

    1. Const A FUN2 ();
    2. Const * FUN3 ();

Once the return value is declared, the const is decorated in accordance with the "cosmetic principle" and acts as a protective function. Const Rational operator* (const rational& LHS,

    1. Const rational& RHS)
    2. {
    3. Return Rational (Lhs.numerator () * Rhs.numerator (),
    4. Lhs.denominator () * Rhs.denominator ());
    5. }

The return value is modified with a const modifier to prevent such an operation from being allowed to occur:

    1. Rational A, B;
    2. Radional C;
    3. (a*b) = C;

It is common to use the const-decorated return value as the object itself (non-reference and pointer) when it is used to overload functions of the two-mesh operator and to produce new objects.

Summarize:

1. In general, when the return value of a function is an object, if it is declared as const, it is used for overloading the operator. In general, it is not recommended to use the const-modifier function's return value type as an object or as a reference to an object. The reason for this is that if the return value is const for an object (const A test = A instance) or a reference to an object is const (const a& test = A instance), the return value has a const property, The return instance can only access the public (protected) data members and the const member functions in Class A, and it is not allowed to be assigned operations, which is rarely used in general cases.

2. If you add a const modifier to a function return value that uses the "pointer Pass" method, the contents of the function return value (that is, the pointer) cannot be modified, and the return value can only be assigned to a const-decorated pointer of the same type. Such as:

    1. const char * GetString (void);

A compilation error will appear in the following statement:

    1. Char *str=getstring ();

The correct usage is:

    1. const char *str=getstring ();

3. There are few occasions when the return value of a function is used as a "reference pass", which is generally only in the predominated value function of the class, and is intended to achieve chain expression. Such as:

    1. Class A
    2. {...
    3. A &operate = (const a &other); Negative value function
    4. }
    5. A A,b,c; A,b,c is an object of a
    6. ...
    7. A=b=c; Normal
    8. (a=b) =c; Not normal, but legal.

If the return value of a negative function is const-modified, the contents of the return value are not allowed to be modified, and the a=b=c in the example above is still correct. (a=b) =c is not correct.

[Think 3]: Is it possible to define an assignment operator overload function?

    1. Const a& operator= (const a& A);

6. Use of Const in class member functions

Usually put in the function body, shape like:

    1. void fun () const;

Any function that does not modify a data member is due to the declaration as a const type. If you inadvertently modify the data member when you write the const member function, or if you call other non-const member functions, the compiler will make an error, which greatly improves the robustness of the program. Such as:

    1. Class Stack
    2. {
    3. Public
    4. void Push (int elem);
    5. int Pop (void);
    6. int GetCount (void) const; Const member functions
    7. Private
    8. int m_num;
    9. int m_data[100];
    10. };
    11. int Stack::getcount (void) const
    12. {
    13. ++m_num; Compilation error, attempting to modify data member M_num
    14. Pop (); Compile error, attempt to invoke non-const function
    15. Return M_num;
    16. }

7. Some suggestions for using const

    • The bold use of const will bring you endless benefits, but only if you have to figure it out;
    • To avoid the most general assignment error, such as assigning a const variable to a value, the concrete visible study questions;
    • Using const in parameters should use a reference or pointer instead of a generic object instance for the same reason;
    • The three usages of const in member functions (parameters, return values, functions) should be used very well;
    • Do not easily set the return value type of the function as const;
    • In addition to overloading operators, it is generally not to make the return value type a const reference to an object;

[Study Questions Answer]

1 This method is incorrect, because the purpose of the declaration pointer is to change the content it points to, and the declared pointer e points to a constant, so it is incorrect;

2 This method is correct, because the content of the declaration pointer is variable;

3 This practice is not correct;

In const a::operator= (const a& A), the use of the const in the argument list is correct, and when such successive assignments are made, the problem arises:

    1. A A,b,c;
    2. (a=b) =c;

Because the return value of a.operator= (b) is a const reference to a, you can no longer assign C to a const constant.

Hope to be of help to you.

C + + Beginner Const usage Explained

Related Article

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.