Before looking at this example, let's take a look at the storage location of the const, const, and static variables in C and C ++. This will give you a comprehensive understanding of const:
The following example shows some very difficult errors of const:
#include
using namespace std;class String{public:friend ostream& operator<<(ostream& os,const String& str); String(char* pstring):pstring_(pstring){ }void display(){pstring_ = "hello";cout << pstring_ << endl;} char& operator[](int index)const{return pstring_[index];} private: char* pstring_; };ostream& operator<<(ostream& os,const String& str){os << str.pstring_;return os;}void f( const String& str){const_cast
(str).display();}void g(String& const str){String a("world");str = a;}//void h(String* const str){}int main(){char a[] = "hello";const String str(a); String ptr("nihao");//const String str("how are you?"); char& c=str[0]; //call const-function c='B'; //modified 'pstring_ ' from outer cout << str << endl;f(str); g(ptr);return 0;}
Let's take a look at the following three statements:
Char a [] = "hello ";
Const String str ();
Char & c = str [0]; // call const-function
C = 'B'; // modified 'pstring _ 'from outer
We have defined a constant String, but this indirect method can be used to modify it. Why? Then how can we avoid this phenomenon?
Our method is to change the return type to the constant type, namely:
Const char & operator [] (int index) const;
In this way, the types are consistent. However, even if the return type is not changed to const, why not:
Const String str ("how are you? ");
Char & c = str [0]; // call const-function
C = 'B'; // modified 'pstring _ 'from outer
Here we have to figure out one thing, that is, for a string, it is saved in the constant area, where the data cannot be changed. At this time, "how are you? "Stored in the constant area (read-only storage area), and when this string is initialized to the object str, it is equivalent to assigning the address of this string to the object's variable pstring _. At this time, the two will point to the same string, so the data in it cannot be changed. The previous assignment of a string to an array attaches a copy of the string to the array, which is stored in the stack and can be modified.
For functions
Void f (const String & str)
{
Const_cast (Str). display ();
}
We can see that the const In the parameter is redundant because it is forcibly converted into a very variable in the function body.
The const in the g and h parameters of the function is not only useless, but also invalid, because the const modifies the form parameter instead of the real parameter, the objects they direct to can still be modified. They can only be transferred to a very large number of parameters and cannot be reset. For example:
G (ptr); after this statement, the ptr value will change to world.
Zookeeper