2

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

vladon
  • 8,158
  • 2
  • 47
  • 91
  • 5
    `public: A(const A &) {}` is almost certainly a mistake – M.M Sep 01 '15 at 05:34
  • @MattMcNabb It occurs frequently in old (pre C++11) code – vladon Sep 01 '15 at 05:35
  • 5
    I've never seen it. What does occur frequently is `private: A(const A &);`. Your version will not disable copying, it will silently allow copying (and might do the wrong thing depending on what the class members are). – M.M Sep 01 '15 at 05:43
  • @MattMcNabb You lucky. I've seen both variants. – vladon Sep 01 '15 at 05:44
  • 4
    You haven't seen *both variants*, you've seen the correct pre-C++11 way to disable copy construction (Matt's version) and a bug (your version). – Praetorian Sep 01 '15 at 06:59

3 Answers3

13

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.

T.C.
  • 133,968
  • 17
  • 288
  • 421
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.

Alexander V
  • 8,351
  • 4
  • 38
  • 47
2

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