我正在为 C++ 中的共享指针编写一个访问器方法,如下所示:
class Foo {
public:
return_type getBar() const {
return m_bar;
}
private:
boost::shared_ptr<Bar> m_bar;
}
所以为了支持 getBar()
的 const-ness返回类型应该是 boost::shared_ptr
防止修改 Bar
它指向。我的猜测是shared_ptr<const Bar>
是我想要返回的类型,而 const shared_ptr<Bar>
将防止重新分配指针本身以指向不同的 Bar
但允许修改 Bar
它指向...但是,我不确定。如果确定知道的人可以确认这一点,或者如果我弄错了,我将不胜感激。谢谢!
最佳答案
你是对的。 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.
同样适用于 weak_ptr
和 unique_ptr
.
关于c++ - `const shared_ptr<T>` 和 `shared_ptr<const T>` 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17793333/