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

2022-01-23 00:00:00 constants c++ boost shared-ptr

I'm writing an accessor method for a shared pointer in C++ that goes something like this:

class Foo {
public:
    return_type getBar() const {
        return m_bar;
    }

private:
    boost::shared_ptr<Bar> m_bar;
}

So to support the const-ness of getBar() the return type should be a boost::shared_ptr that prevents modification of the Bar it points to. My guess is that shared_ptr<const Bar> is the type I want to return to do that, whereas const shared_ptr<Bar> would prevent reassignment of the pointer itself to point to a different Bar but allow modification of the Bar that it points to... However, I'm not sure. I'd appreciate it if someone who knows for sure could either confirm this, or correct me if I got it wrong. Thanks!

解决方案

You are right. shared_ptr<const T> p; is similar to const T * p; (or, equivalently, T const * p;), that is, the pointed object is const whereas const shared_ptr<T> p; is similar to T* const p; which means that p is const. In summary:

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.

The same holds for weak_ptr and unique_ptr.

相关文章