C + + in const usage

Source: Internet
Author: User

Attention

    • Const object implicitly feels the local variable of the file

When a non-const variable is defined in the global scope , it can be visited throughout the program. We can define a non-const variable in a file, and if the appropriate declaration has been made, it can be used in another file:

differs from other variables unless specifically stated. A const variable declared at the global scope is a local variable that defines the file for that object.

This variable exists only in that file and cannot be interviewed by other files. By specifying the const variable as extern. will be able to access the const object throughout the program.

Note: The non-const variable implicitly feels extern.

To make the const variable accessible in other files, you must explicitly specify it as extern in the file.


-------------const pointer, const reference, const reference shape--------------------

"1" const modifier pointers and references

1. The term "Const reference" is "a reference to a const object", which is customary to say a const reference to a non-const reference.

Unlike pointers, the "const pointer" in the pointer is different from the pointer to a const object.

2. It is worth noting that the const reference and pointers to the const object have one thing in common: a const reference can point to a const object and to a non-const object, as well as a pointer to a const object.

3. For a const pointer and a pointer to a const object, give a very easy example

123456 int m=1, n=5;constint*p1=&m;   //指向const对象的指针:const修饰的是*p1, 即*p1的值是仅仅读的;可是p1这个指针是能够改动的。int * const p2=&n; //const指针:const修饰的是p2, 即p2这个指针是仅仅读的;可是*p2的值是能够改动的。p1=&n;             //p1的指针改动为变量n的地址,而这个地址就是p2,相当于p1=p2;*p2=3;             //*p2的值改动为3。当然*p1的值也就是3printf("%d %d\n",*p1,*p2);

The advantage of the "2" shape for a const reference

When it comes to Const, we have to mention the shape of the const reference type and really understand the merit of the const reference form, only to find it really wonderful

A brief summary. Welcome to Supplement

A. When the type of the actual participation is relatively large. The replication overhead is very large (when the shape is initialized), and the reference "avoids copying."

(This is often used when passing class objects)

B. "Avoid changes to the actual participation". When using references, it is assumed that the caller wants to use only the actual participation and does not alter the actual participation. The const can avoid using this reference to change the actual

C. More usability than non-const reference form participation: The form can be initialized with a const object, using the actual participation of a literal or rvalue expression.

The following shows a sample example

12345678 a. voidsearch(constvector<int> & vec) 避免了实參的复制开销b. 同a例。可避免对实參做出改动c. 例如以下函数,调用时void search(string & s);         调用: search("hello");// Error 实參为字面值常量void search(const string & s);   调用: search("hello");// OK再如void search(int & v);            调用: search(v1+v2);  // Error 实參是一个右值。无法给引用赋值(须要左值)void search(const int & v);      调用: search(v1+v2);   // OK

---------------Const----------------------------------------in the class

Generally speaking. With the const modifier function, the function must be a class member function.

The "1" Const object can only call the const member function non-const object to be able to invoke the const member function

Explanation: You cannot assign a pointer to a const object to a non-const object pointer, and you agree to assign a non-const object pointer to a pointer to a const object.

Why do you explain that? This originates from what happens when the member function is called:

What happens when a member function is called: Binds the calling object to the function, and initializes the member function to the address of the calling object.

Therefore, the Const object passes the actual address as const class * const this. Instead of the const member function being called, the *const of the class is used, and the result is that the pointer to the const object is assigned to a pointer to a non-const object, which is not agreeable. So a const object can only invoke the const member function. In the same vein, a non-const object, when calling a const member function, essentially assigns a pointer to a non-const object (the actual argument) to the const object pointer (the form participates), which is also possible. Therefore, non-const objects can invoke the const member function.

The "2" Const member variable cannot be altered and must be assigned a value in the initialization list.

The const member function cannot change member variables and cannot invoke non-const member functions (that is, attempts to change values)

Conversely, non-const member functions can of course call the const member function

return value for "3" Const member function: value type & Const reference type (non-const reference not returned)

1234567891011 example.classVec{private:    vector<string> textVec;public:    conststring & text_line(size_tlineNum)const    {        returntextVec.at(lineNum-1);    }};

Assuming that the member function is const, the object calls the constant function passing this when it has become a const object, assuming that the function is written in the form

1234 string & text_line(size_tlineNum)const{    returntextVec.at(lineNum-1);}

Compile error: You cannot convert a const string to a string &, because this is equivalent to pointing a non-const reference to a const type variable. Therefore, to return a reference, it must be a const reference.

------------The return value type---

There are, of course, other ways to make the return value of a function a value type, which is

1234 string text_line(size_tlineNum)const{    returntextVec.at(lineNum-1);}

This is actually a memory copy, because string is a class type, some people will ask, so this is not equivalent to a const object assigned to a non-const object?

For the above function, the copy construction of the string is actually called, and the copy construction is the const string type. This also involves the question of the const type as a parameter. The above has been said

The return value for a function is a value type, which is nothing more than two, a normal built-in type. An assignment operation; A class type that invokes a copy construct for a memory copy. For example, the following:

1234 constinta = 9;intb = a;   (int&bb = a; // error)  // 赋值constset<int> s;set<int> ss = s;  // 内存拷贝

So we should pay attention to:

You cannot assign a const object pointer or reference to a pointer or reference to a non-const object. However, you can initialize a const object to a non-const object;

The reciprocal assignment of const and non-const at the object level (not reference or pointer level) is agreed. Reversible; just like

123 constinta = 9;intaa = a;constintaaa = aa;

-------------------Const and Overloaded---------------------------------------

There are two types of const overloads, one based on whether the function type is const or not, and one that is based on whether the class member function is a const overload

"1" is an overload based on whether the function type is const

When and only if the shape participates in a reference or pointer type. Whether the shape participates in a const effect

-----Reference type----

A function-based reference can be a pointer to a const object or to a non-const object, implementing overloading, as shown in the following scale:

123456 A: voidsearch(Student &);B: voidsearch(constStudent &);constStudent a;Student b;search(a);  // 调用Bsearch(b);  // 调用A

Note: According to the above, we know that assuming that the shape is a normal reference, you cannot pass a const object to the shape.

Assume that a non-const object is passed. As mentioned above, both functions are feasible because non-const objects can be used both to initialize a const reference or to initialize a non-const reference. So there's no ambiguity?

This is the principle that the compiler follows when calling a function, first of all, "exact match," and we know that initializing a const reference to a non-const object requires an implicit conversion. So the exact match is not met, so call a.

-----pointer type----

Const overloads based on pointer-shaped participation are the same as references.

There is just one problem to note:

The above term says that a const reference is a reference to a const object, which is different from a const pointer and a pointer to a const object.

So note: You cannot overload a function based on whether the pointer itself is const

1234 voidsearch(int * ptr);void search(int * constptr);// 这不能实现重载,指针本身是否const并不会带来差别// 在函数调用时,形參都复制了指针的值

"2" is an overload based on whether the class member function is const

In a class, you can overload a member function, such as the following, based on whether the member function is const

1234567891011121314 classVec{private:    vector<string> textVec;public:    conststring & text_line(size_tlineNum)const    {        returntextVec.at(lineNum-1);    }    string & text_line(size_tlineNum)    {        returntextVec.at(lineNum-1);    }};

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

C + + in const usage

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.