`shared_ptr`打破对象的常量

`shared_ptr` breaks constness of the object

本文关键字:对象 常量 shared ptr      更新时间:2023-10-16

考虑以下代码:

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

在这段代码(2)中,get_b是一个常量函数,a是一个const对象,这一事实在没有任何错误或警告的情况下独立编译。

我的问题是你如何处理这种情况?我能使用的最好的方法是将(1)更改为以下内容:

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

但我应该永远记住,我应该将const添加到返回类型中。那不是很方便。有更好的方法吗?

这实际上与共享指针本身无关。我的意思是,如果你有一个普通指针,你会遇到完全相同的问题,并以完全相同的方式解决它,那就是

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

如果你把它像一样留下

B* get_b() const {return b_; }

你也会有同样的问题。

好吧,你自己已经找到了解决方案。

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

这是唯一正确的方法。