C++'s mutable and conceptual constness
http://www.highprogrammer.com/alan/rants/mutable.html
Most of time mutable is described as a type which breeches the constness of the object. But it is actually to help constness for many purposes. eg.
1) Reference count of a the objects users.
2) Use it in the for storing the mutex object in the object so that you can apply lock when reading something from const object.
3) You can use it for a lazy evaluation of an expression object..
i.e.
class PI{
public:
pi():pi(0.0), evaluated(false) {}
double getValue(){
if(evaluated) return _pi;
for(int i=0; i< 1000000000000; i++){
//....
}
evaluated=true;
return _pi;
}
private:
mutable double _pi;
mutable bool evaluated;
};
In that case you can create and pass object of PI to any function as const, and it will be evaluated on use only.
How mutable will benefit you is design of the function which takes PI as input.
void PrintCircleAreaWithRadius(double radius, const PI& pi); //If _pi in PI class is not declared as mutable compiler will not allow you ..
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment