The point of existence of a const object is to ensure that it will not be changed during some procedure. This is completely due to the fact that you tell other developers your goal and provide the optimizer with information, since const does not exist at the level of machine code.
Const const, , const, , , const. const, , , const .
, , . , , , . , , const. , toString(), ( ). , , , , .
class ImmutableClass
{
private:
std::string strTextRepresentation;
public:
int nValue1, nValue2, nValue3;
ImmutableClass(int nValue1, int nValue2, int nValue3):
nValue1(nValue1), nValue2(nValue2), nValue3(nValue3)
{
std::stringstream ss;
ss << nValue1 << ',' << nValue2 << ',' << nValue3;
strTextRepresentation = ss.str();
}
const std::string& toString() const
{
return strTextRepresentation;
}
};
, , , mutable. , " " . , , (, , , - toString()).
class ImmutableClass
{
private:
mutable std::string strTextRepresentation;
public:
int nValue1, nValue2, nValue3;
ImmutableClass(int nValue1, int nValue2, int nValue3):
nValue1(nValue1), nValue2(nValue2), nValue3(nValue3)
{
}
const std::string& toString() const
{
if (strTextRepresentation.size() == 0)
{
std::stringstream ss;
ss << nValue1 << ',' << nValue2 << ',' << nValue3;
strTextRepresentation = ss.str();
}
return strTextRepresentation;
}
};
, , , , , . const_cast-ing , , , , , . const_cast , .