Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep this const-correct without cheating the compiler?

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)?

like image 816
laurent Avatar asked Dec 06 '25 03:12

laurent


2 Answers

You could make a proxy member object which you declare mutable and which encapsulates the lazy-loading policy. That proxy could itself be used from your const function. As a bonus you'll probably end up with some reusable code.

like image 119
Kerrek SB Avatar answered Dec 08 '25 17:12

Kerrek SB


I would forward the call to a proxy object which is a mutable member of this class, something like this:

class Example {

    public:

        int getSomeProperty(int id) const
        {
            m_proxy.LazyLoad();
            return m_proxy.getProperty(id);
        }

    private:

        struct LazilyLoadableData
        {
             int GetProperty(int id) const;
             void LazyLoad();
       };

     mutable LazilyLoadableData m_proxy;
};
like image 33
Nawaz Avatar answered Dec 08 '25 17:12

Nawaz