laurent
laurent

Reputation: 90863

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:

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

Upvotes: 3

Views: 184

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361802

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;
};

Upvotes: 3

user743382
user743382

Reputation:

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.

No, it's not making some changes, at least not from the viewpoint whoever called getSomeProperty. All changes, if you're doing it right, are purely internal, and not visible in any way from the outside. This is the solution I'd choose.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477660

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.

Upvotes: 4

Related Questions