简体   繁体   English

删除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 {} ? 为什么delete要比{}

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. 一个空的拷贝构造函数可以很好地调用,它只是默认初始化类成员,而不是进行任何拷贝。

Why delete is better than {} ? 为什么delete要比{}

Because you're highly unlikely to actually want the weird "copy" semantics an empty copy constructor would provide. 因为您实际上不太可能需要一个空的复制构造函数来提供怪异的“复制”语义。

One reason is syntactic sugar -- no longer need to declare the copy constructor without any implementation. 原因之一是语法糖-无需任何实现就无需声明复制构造函数。 The other: you cannot use deleted copy constructor as long as compiler is prohibited from creating one and thus first you need to derive new class from that parent and provide the copy constructor. 另一个:只要禁止编译器创建一个副本,就不能使用已删除的副本构造函数,因此首先需要从该父对象派生新类并提供副本构造函数。 It is useful to force the class user to create own implementation of it including copy constructor for specific library class. 强制类用户创建它自己的实现,包括针对特定库类的复制构造函数,这很有用。 Before C++ 11 we only had pure virtual functions with similar intent and the constructor cannot be virtual by definition. 在C ++ 11之前,我们只有具有相似意图的纯虚函数,并且构造函数根据定义不能是虚的。

The default or existing empty copy constructor does not prevent an incorrect use of the class. 默认或现有的空副本构造函数不会防止错误使用该类。 Sometimes it is worth to enforce the policy with the language feature like that. 有时值得通过这种语言功能来实施该策略。

Empty Copy constructor is used for default initializing the member of class. 空副本构造函数用于默认初始化类的成员。 While delete is use for prevent the use of constructor. 虽然delete用于防止使用构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM