我正在学习std::shared_ptr
。
我阅读了一篇有关 shared_ptr
构造函数的文档来找到它的复制构造函数。
我可以找到一个构造函数,
shared_ptr( const shared_ptr& r );
但它似乎不是我期望的简单复制构造函数,
shared_ptr( shared_ptr& r );
而且它似乎不共享引用计数器。
为什么shared_ptr
没有简单的复制构造函数?
以防万一,我在下面写下我真正想做的事情,
class A {
public:
A(shared_ptr<X>& sptr) : sptr_(sptr) {}
private:
shared_ptr<X> sptr_;
};
最佳答案
Why shared_ptr does not have a simple copy constructor?
标准规定:
A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, [...]
没有什么简单的复制构造函数。 std::shared_ptr
有一个完全有效的复制构造函数。它构造一个 std::shared_ptr
对象,与给定对象共享所有权(如果有效)。
关于c++ - std::shared_ptr<X> 是否有复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42130940/