`shared_ptr`打破了对象的常量

时间:2011-06-22 09:08:30

标签: c++ c++11 const shared-ptr

请考虑以下代码:

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是一个const函数而a是一个const对象。

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

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

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

1 个答案:

答案 0 :(得分:13)

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

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

如果你把它留下了

B* get_b() const {return b_; }

你有同样的问题。

嗯,你自己找到了解决方案。

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

这是唯一正确的方法。