shared_ptr breaks an object constant

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) is compiled without any errors or warnings, regardless of what the get_bconst function is, but it ais 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 must always remember what I must add constto the return type. This is not very convenient. Is there a better way?

+5
source share
1 answer

. , , , ,

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

B* get_b() const {return b_; }

.

, .

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

.

+13

All Articles