Search code examples
c++c++11constantsshared-ptr

`shared_ptr` breaks constness of the object


Consider the following code:

class B 
{
    int x;
public:
    B() : x( 10 ) {}
    int get_x() const { return x; }
    void set_x( int value ) { x = value; }
};

class A
{
    boost::shared_ptr<B> b_;
public:
    boost::shared_ptr<B> get_b() const { return b_; } // (1)
};

void f( const A& a)
{
    boost::shared_ptr<B> b = a.get_b();
    int x = b->get_x();
    b->set_x( ++x ); // (2)
}

int main()
{
    A a;
    f( a );

    return 0;
}

In this code (2) compiles without any errors or warnings independently the fact that get_b is a const function and a is a const object.

My question is how do you deal with this situation? The best I could use is to change (1) to the following:

boost::shared_ptr<const B> get_b() const { return b_; } // (1)

But I should always remember that I should add const to the return type. That's not very convenient. Is there a better way?


Solution

  • This doesn't actually have anything to do with shared pointers per se. I mean if you had a plain pointer you'd have exactly the same problem and would solve it in exactly the same way, that is

    const B* get_b() const {return b_; }
    

    If you left it like

    B* get_b() const {return b_; }
    

    you'd have the same problem.

    Well, you have found the solution yourself.

    boost::shared_ptr<const B> get_b() const { return b_; } // (1)
    

    It's the only const-correct way to do it.