What is the proper way to implement a getter method for a lazily-initialized member variable and maintain const-correctness? That is, I would like to have my getter method be const, because after the first time it is used, it’s a normal getter method. It is only the first time (when the object is first initialized) that const does not apply. What I would like to do:
class MyClass {
MyClass() : expensive_object_(NULL) {}
QObject* GetExpensiveObject() const {
if (!expensive_object_) {
expensive_object = CreateExpensiveObject();
}
return expensive_object_;
}
private:
QObject *expensive_object_;
};
Can I eat my cake and have it too?
I propose encapsulating James Curran‘s answer into a class of its own if you do this frequently:
Now use this in your code as follows: