Creating a class that cannot be copied: private methods undefined vs Remote methods

Before C ++ 11, I saw this code:

class Car {
public:
  Car() {}
private:
  Car(const Car&);
  Car& operator=(const Car&);
};

For C ++ 11 (and later), I see the code as follows:

class Car {
public:
  Car() {}
private:
  Car(const Car&) = delete;
  Car& operator=(const Car&) = delete;
};

Do they behave the same? If not, explain.

Link: https://ariya.io/2015/01/c-class-and-preventing-object-copy

+4
source share
4 answers

=deletewill give more meaningful error messages. A message about a remote function tells you that it does not exist, and no one can create an object with the specified constructor. To say that this is personal, this information is not provided - it simply says that the caller cannot call it, and not that no one can.

, , / ( ).

https://godbolt.org/g/06R9AQ

+5

, .

, :

int main() {
    Car c;
    Car other{c};
}

. , , , , . delete , Car . private ( , ) , , , private .

, :

void Car::foo() {
    Car c;
    Car other{c}; 
}

delete, . private - . - . , ? delete .

11 ++ undefined.

+5

Car& operator=(const Car&) = delete; " ".

= delete; , Bjarne blog:

struct Z {
    // ...

    Z(long long);     // can initialize with an long long
    Z(long) = delete; // but not anything less
};
+3

, ​​ , - :

' (const Car &)'

, - .
, delete d copy , :

class Car {
public:
  Car() {}
// private: <-- this should not be here
  Car(const Car&) = delete;
  Car& operator=(const Car&) = delete;
};

, , - :

'Car (const Car &)'

, , .
, , factory .

In any case (no longer the case), the new features are not free, and using them in a way that is not intended will not give the expected benefits.

+3
source

Source: https://habr.com/ru/post/1656891/


All Articles