I have a C++ class like that:
class Example { public: int getSomeProperty(int id) const; private: lazilyLoadSomeData(); } Basically getSomeProperty() return some data that has been loaded using lazilyLoadSomeData(). Since I don't want to load this data until needed, I'm calling this method within getSomeProperty()
int Example::getSomeProperty(int id) const { lazilyLoadSomeData(); // Now the data is loaded return loadedData[id]; } This does not work since lazilyLoadSomeData() is not const. Even though it only changes mutable data members, the compiler won't allow it. The only two solutions I can think of are:
Load the data in the class constructor, however I do not want to do that, as lazily loading everything makes the application faster.
Make
lazilyLoadSomeData()const. It would work since it only changes mutable members, but it just doesn't seem right since, from the name, the method is clearly loading something and is clearly making some changes.
Any suggestion on what would be the proper way to handle this, without having to cheat the compiler (or giving up on const-correctness altogether)?
mutablekeyword is for. an alternative which is more in the "cheating" direction is to keep a pointer to the data. i'm mentioning that for the express purpose of recognizing that anti-pattern and avoiding it; do usemutablefor lazy data. cheers & hth.,