【发布时间】:2013-07-21 12:40:06
【问题描述】:
我正在为 C++ 中的共享指针编写一个访问器方法,如下所示:
class Foo {
public:
return_type getBar() const {
return m_bar;
}
private:
boost::shared_ptr<Bar> m_bar;
}
所以为了支持getBar() 的常量性,返回类型应该是boost::shared_ptr,它可以防止修改它指向的Bar。我的 猜测 是 shared_ptr<const Bar> 是我想要返回的类型,而 const shared_ptr<Bar> 会阻止重新分配指针本身以指向不同的 Bar 但允许修改 @它指向的 987654328@... 但是,我不确定。如果确定知道的人可以确认这一点,或者如果我弄错了,我将不胜感激。谢谢!
【问题讨论】:
-
正是你所说的。您可以查看操作员
*和->的文档来确认这一点。 -
T *const和T const *有什么区别?一样。 -
@H2CO3 一点也不。
const通常会修改 _precedes 的内容,因此T *const是指向T的const指针,T const*是指向constT的指针。最好避免使用前面没有任何内容的const。 -
@JamesKanze,这就是H2CO3的意思:
T *const和T const *之间的区别与const shared_ptr<T>和shared_ptr<const T>之间的区别相同 -
@H2CO3 我误解了您所说的“相同”的含义。但是我很好奇一件事:你写
T *const,那你为什么不写shared_ptr<T> const呢?同样,你写了T const*,那为什么不写shared_ptr<T const>呢?为什么不正交,并把const放在任何地方(因为在某些情况下你必须把它放在后面)。
标签: c++ boost constants shared-ptr