如何为继承自 std::enable_shared_from_this 的 class 显式初始化复制构造函数
How do I explicitely initialize the copy constructor for a class that inherits from std::enable_shared_from_this
考虑以下测试代码:
#include <memory>
class C : public std::enable_shared_from_this<C>
{
public:
C(C const& c){}
};
int main()
{
}
Compiling this 与 -Wextra
将生成以下警告
warning: base class 'class std::enable_shared_from_this' should be explicitly initialized in the copy constructor [-Wextra]
如何正确执行此操作?有什么我可以在更复杂的地方绊倒的吗类?
您可以像这样调用其默认构造函数来显式初始化它:
C(C const& c) : enable_shared_from_this() {}
你也可以像这样调用它的拷贝构造函数来实现:
C(C const& c) : enable_shared_from_this(c) {}
复制构造函数实际上与默认构造函数做同样的事情(它将当前对象标记为不属于 shared_ptr
)这确保以下将做明智的事情:
C(C const& c) = default; // also calls the copy constructor of the enable_shared_from_this base
复制一个对象时,您会得到一个新对象,因此,显然,它不属于另一个对象所拥有的 shared_ptr
。
考虑以下测试代码:
#include <memory>
class C : public std::enable_shared_from_this<C>
{
public:
C(C const& c){}
};
int main()
{
}
Compiling this 与 -Wextra
将生成以下警告
warning: base class 'class std::enable_shared_from_this' should be explicitly initialized in the copy constructor [-Wextra]
如何正确执行此操作?有什么我可以在更复杂的地方绊倒的吗类?
您可以像这样调用其默认构造函数来显式初始化它:
C(C const& c) : enable_shared_from_this() {}
你也可以像这样调用它的拷贝构造函数来实现:
C(C const& c) : enable_shared_from_this(c) {}
复制构造函数实际上与默认构造函数做同样的事情(它将当前对象标记为不属于 shared_ptr
)这确保以下将做明智的事情:
C(C const& c) = default; // also calls the copy constructor of the enable_shared_from_this base
复制一个对象时,您会得到一个新对象,因此,显然,它不属于另一个对象所拥有的 shared_ptr
。