Break C ++ Const rules and cconst rules
Starting with a C ++ cainiao Function
1 CString MyClass::GetStringValue() const2 {3 return m_strValue; 4 }
This value may not have been assigned a value. Well, I will first judge whether it is null. If it is null, it will be assigned a value.
CString MyClass::GetStringValue() const{ if(m_strValue.IsEmpty()) SetStringValue(); return m_strValue; }
As a result, the compilation fails because there is a rule that the const function cannot call non-const functions.
See the following compilation error:
Error C2662: "MyClass: SetStringValue": the "this" pointer cannot be converted from "const MyClass" to "MyClass &"
Hey, it turns out that when we define a member function of a class, a this pointer will be passed in by default, but if it is a const function, will it be passed to a const pointer? So I want the compiler to see this:
CString MyClass::GetStringValue(const MyClass* this){ if(this->m_strValue.IsEmpty()) this->SetStringValue(); return this->GetStringValue();}
After verification, we created a static function to simulate it:
CString MyClass::GetStringValueS(const MyClass* mcp){ if(mcp->m_strValue.IsEmpty()) mcp->SetStringValue(); return mcp->GetStringValue();}
Compile to get the same error:
Error C2662: "MyClass: SetStringValue": the "this" pointer cannot be converted from "const MyClass" to "MyClass &"
So I tried to break the const rule:
CString MyClass::GetStringValue()const{ MyClass * nonconstthis = (MyClass *)this; if(m_strValue.IsEmpty()) nonconstthis->SetStringValue(); return m_strValue;}
The result is compiled successfully, and the execution is normal.
Therefore, there is a conversion const_cast <> specifically to do this:
CString MyClass::GetStringValue()const{ if(m_strValue.IsEmpty()) const_cast<MyClass *>(this)->SetStringValue(); return m_strValue;}
Finally, I think this is against the original intention of the const design. This is a kind of deception for callers (against the contract: I promise not to change you), so it is not recommended to use it like this.