Dav*_*hun 104 c++ boost const shared-ptr
我正在为C++中的共享指针编写一个访问器方法,如下所示:
class Foo {
public:
return_type getBar() const {
return m_bar;
}
private:
boost::shared_ptr<Bar> m_bar;
}
Run Code Online (Sandbox Code Playgroud)
因此,为了支持getBar()返回类型的常量应该是一个boost::shared_ptr阻止Bar它指向的修改.我的猜测是shared_ptr<const Bar>我希望返回的类型,但是const shared_ptr<Bar>会阻止指针本身的重新分配指向不同Bar但允许修改Bar它指向的......但是,我不确定.我很感激,如果有人知道肯定可以证实这一点,或者如果我弄错了就纠正我.谢谢!
Cas*_*eri 147
你是对的.shared_ptr<const T> p;类似于const T * p;(或等效地T const * p;),即,指向的对象是,const而const shared_ptr<T> p;类似于T* const p;指的p是const.综上所述:
shared_ptr<T> p; ---> T * p; : nothing is const
const shared_ptr<T> p; ---> T * const p; : p is const
shared_ptr<const T> p; ---> const T * p; <=> T const * p; : *p is const
const shared_ptr<const T> p; ---> const T * const p; <=> T const * const p; : p and *p are const.
Run Code Online (Sandbox Code Playgroud)
同样适用于weak_ptr和unique_ptr.