`shared_ptr`打破了对象的常量

Kir*_*sky 5 c++ const shared-ptr c++11

请考虑以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

在这段代码中,(2)独立编译没有任何错误或警告,这get_b是一个const函数并且a是一个const对象.

我的问题是你如何应对这种情况?我可以使用的最好的是将(1)更改为以下内容:

boost::shared_ptr<const B> get_b() const { return b_; } // (1)
Run Code Online (Sandbox Code Playgroud)

但我应该永远记住,我应该添加const返回类型.那不是很方便.有没有更好的办法?

Arm*_*yan 13

这实际上与共享指针本身没有任何关系.我的意思是,如果你有一个普通的指针你会有完全相同的问题,并以完全相同的方式解决它,也就是说

const B* get_b() const {return b_; }
Run Code Online (Sandbox Code Playgroud)

如果你离开它就好

B* get_b() const {return b_; }
Run Code Online (Sandbox Code Playgroud)

你有同样的问题.

好吧,你自己找到了解决方案.

boost::shared_ptr<const B> get_b() const { return b_; } // (1)
Run Code Online (Sandbox Code Playgroud)

这是唯一正确的方法.