1

I have seen a lot of books recommend using =delete, is this just clear what it means? (making the program more readable) rather than saying that it is a bad thing to set the copy constructor to private? Thinks your answers

class A {
  A(const A&);
  // some functions and variable

public:
  // or you can A(const A&)=delete;
  // do something
};     
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
AndyLi
  • 81
  • 3
  • Are you asking about `=delete` or `=default`? – interjay Nov 17 '19 at 13:23
  • `defalut` is not a keyword in C++. If you meant `default` the question does not make too much sense (or has a very quick answer): a class with an inaccessible copy c-tor is not copyable, a class with a defaulted copy c-tor is. Are you sure you didn't mean `delete` (as in the original revision)? – The Vee Nov 17 '19 at 13:35
  • My poor English...I wil Edit my question.sorry – AndyLi Nov 17 '19 at 13:41
  • `pubilc` is also a typo in your posts. – Peter Nov 17 '19 at 13:45

1 Answers1

1

This is a relatively new functionality (added in the 2011 revision of C++) whose main motivation surely was readability and clarity of intent. However, the difference is more than just cosmetic.

Remember that with a constructor declared in the class, nothing prevents some other translation unit from actually providing the definition. It is quite usual to just list a class' member functions in a header file and implement them in a separate .cpp. If someone uses the copy constructor from inside the class, the compiler will complain that the definition is missing ("undefined reference to..."). If a naive programmer somehow reaches the conclusion that you forgot to implement it because you never needed it, they can go ahead and do so. Suddenly your class is copyable, even though only from within its own member functions (and friends). The =delete constructor prevents this, and the compiler errors are nicer (usually along the lines of "the object can't be copied because the copy constructor was declared as deleted" rather than "undefined reference to ..." or "A::A is private within this context").

The Vee
  • 11,420
  • 5
  • 27
  • 60