Deleted vs empty copy constructor

若如初见. 提交于 2019-12-12 03:17:47

问题


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 {}?


回答1:


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 {}?

Because you're highly unlikely to actually want the weird "copy" semantics an empty copy constructor would provide.




回答2:


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.

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.




回答3:


Empty Copy constructor is used for default initializing the member of class. While delete is use for prevent the use of constructor.



来源:https://stackoverflow.com/questions/32323640/deleted-vs-empty-copy-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!