`shared_ptr`打破对象的常量
`shared_ptr` breaks constness of the object
考虑以下代码:
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)
这是唯一正确的方法。
相关文章:
- 代理对象的常量正确性
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 如何使用数据对象上的常量指针初始化类
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 为什么当我们有常量引用时创建临时对象?
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- C++,如何使用常量对象和非常量对象进行比较?
- 通过从构造函数中的'this'复制的指针改变常量对象
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- C++将常量字符* 指针数组传递给对象
- C++ 对非常量对象的常量引用和对非常量对象的非常量引用之间的区别
- 未定义的对象(〔basic.life〕/8):为什么允许引用重新绑定(和常量修改)
- 当类具有常量时,将对象插入到向量中
- 算法不适用于非常量对象的const_iterator
- C++:允许临时对象调用非常量成员函数的设计理念是什么?
- 为什么MSVC14允许声明指向动态未初始化常量对象的指针
- 可作为常量调用的比较对象
- C++中的常量对象或私有/常量数据成员(变量)?
- 将值从指针复制到常量对象参数
- 如何正确组合可变对象常量