从boost::shared_ptr<T>转换为boost::shared_ptr<const T>

3
class T
{};

class UseT
{
public:
    //...
    boost::shared_ptr<const T> getT() const
    {
        return m_t;
    }
private:
    boost::shared_ptr<T> m_t;
};

问题> 当我们将boost::shared_ptr<T>转换为boost::shared_ptr<const T>时使用的规则是什么?

1个回答

1

shared_ptr<T>有一个转换构造函数,允许从shared_ptr<U>构造它,如果从U*T*的转换是有效的,这与内置指针的工作方式相同。

template<typename U>
  shared_ptr(const shared_ptr<U>& other);

对于 std::shared_ptr,只有在 U* 可转换为 T* 时才能调用构造函数,但是对于 boost::shared_ptr 我不确定是否会检查,或者您只会因为无效的转换而得到编译器错误。
由于 T* 可以转换为 const T*,所以构造函数允许您从 shared_ptr<T> 创建一个 shared_ptr<const T>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接