c++ - `const shared_ptr<T>` 和 `shared_ptr<const T>` 之间的区别?

标签 c++ boost constants shared-ptr

我正在为 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; ),也就是说,指向的对象是 constconst shared_ptr<T> p;类似于 T* const p;这意味着 pconst .总结:

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_ptrunique_ptr .

关于c++ - `const shared_ptr<T>` 和 `shared_ptr<const T>` 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17793333/

相关文章:

c++ - C++ 中的 Fast(est) 可变堆实现

c - ANCI C (C90) : Can const be changed?

Javascript:常量属性

c++ - CMake - target_link_libraries 和真实的库名称

c++ - 使用 xcode 写出二进制文件

c++ - 在 Windows 上从 1_55 更新到 1_62 后,创建一个 boost::asio::ip::udp::socket 在 LIB 中崩溃

c++ - 包装 boost::geometry::Point 访问器的 Cythonic 方式

c - #define 与 static const 的优化(在 avr-gcc 中)

c++ - 在没有 Main 的情况下编译 C 程序

c++ - Std::vector 填充时间在某个阈值后从 0ms 变为 16ms?