删除vs空副本构造函数 [英] Deleted vs empty copy constructor
问题描述
空和删除副本构造函数的示例:
Examples of empty and deleted copy constructors:
class A
{
public:
// empty copy constructor
A(const A &) {}
}
class B
{
public:
// deleted copy constructor
A(const A&) = delete;
}
他们在实践中是否也这样做(禁止复制对象)?为什么删除
比 {}
好?
Are they doing the same in practice (disables copying for object)? Why delete
is better than {}
?
推荐答案
他们在实践中是否这样做(禁用对象复制)?
Are they doing the same in practice (disables copying for object)?
否。尝试调用已删除的函数会导致编译时错误。空拷贝构造函数可以很好地调用,它只是默认初始化类成员而不进行任何复制。
No. Attempting to call a deleted function results in a compile-time error. An empty copy constructor can be called just fine, it just default-initializes the class members instead of doing any copying.
为什么
删除
比{}
好吗?
因为您极不可能实际希望使用空副本构造函数提供的怪异的复制语义。
Because you're highly unlikely to actually want the weird "copy" semantics an empty copy constructor would provide.
这篇关于删除vs空副本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!