Prior to C++11, I saw code like this:
class Car {
public:
Car() {}
private:
Car(const Car&);
Car& operator=(const Car&);
};
For C++11 (and later), I see code like this:
class Car {
public:
Car() {}
private:
Car(const Car&) = delete;
Car& operator=(const Car&) = delete;
};
Do they behave identically? If not, please explain.
Ref: https://ariya.io/2015/01/c-class-and-preventing-object-copy
They are similar in most respects, but differ in some others.
Consider the following external code trying to copy objects of the class:
int main() {
Car c;
Car other{c};
}
Both of these versions will cause the above code to fail. At this point, though, the developer would look at the interface to see why. With the delete
version, it's obvious that Car
was not meant to be copied. With the private
version, (at least without a comment), it raises a doubt whether the copy constructor was perhaps placed in the private
section by accident.
Now consider member code trying to copy objects of the class:
void Car::foo() {
Car c;
Car other{c};
}
The delete
version fails like before. The private
version is a link error. This raises an even greater doubt - it's not uncommon to forget to define a method that has been declared. Perhaps this is what's happened here? The delete
version doesn't have this problem.
Edit Scott Meyers discusses this in Item 11 of Effective Modern C++ Prefer deleted functions to private undefined ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With