Reputation: 8401
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 {}
?
Upvotes: 2
Views: 1970
Reputation: 109
Empty Copy constructor is used for default initializing the member of class. While delete is use for prevent the use of constructor.
Upvotes: 2
Reputation: 8698
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.
Upvotes: 2
Reputation: 137315
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.
Upvotes: 13