- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 420字
- 2021-06-10 18:28:15
Accessing const objects
You have seen many examples so far of using const, and perhaps the most frequent is when it is applied to a reference as a function parameter to indicate to the compiler that the function only has read-only access to the object. Such a const reference is used so that objects are passed by reference to avoid the overhead of the copying that would occur if the object were passed by value. Methods on a class can access the object data members and, potentially, can change them, so if you pass an object through a const reference the compiler will only allow the reference to call methods that do not change the object. The point class defined earlier had two accessors to access the data in the class:
class point
{
double x; double y;
public:
double get_x() { return x; }
double get_y() { return y: }
};
If you define a function that takes a const reference to this and you attempt to call these accessors, you will get an error from the compiler:
void print_point(const point& p)
{
cout << "(" << p.get_x() << "," << p.get_y() << ")" << endl;
}
The error from the compiler is a bit obscure:
cannot convert 'this' pointer from 'const point' to 'point &'
This message is the compiler complaining that the object is const, it is immutable, and it does not know whether these methods will preserve the state of the object. The solution is simple--add the const keyword to methods that do not change the object state, like this:
double get_x() const { return x; }
double get_y() const { return y: }
This effectively means that the this pointer is const. The const keyword is part of the function prototype, so the method can be overloaded on this. You can have one method that is called when it is called on a const object and another called on a non-const object. This enables you to implement a copy-on-write pattern where, for example, a const method would return read-only access to the data and the non-const method would return a copy of the data that is writeable.
Of course, a method marked with const must not alter the data members, not even temporarily. So, such a method can only call const methods. There may be rare cases when a data member is designed to be changed through a const object; in this case the declaration of the member is marked with the mutable keyword.