2017-10-14 13 views
6

Warum dies:Explizit gelöscht Bewegung Konstruktor

struct A 
{ 
    A(int) { 
     cout << "construct from int" << endl; 
    } 

    A(A&&) = delete; 

    A(const A &) { 
     cout << "copy constructor" << endl; 
    } 
}; 

int main(){ 
    A a = 0; 
} 

gibt mir eine Fehlermeldung:

error: use of deleted function ‘A::A(A&&)’ 

Und warum, wenn ich solchen Schritt Konstruktor

A(A&&) { 
    cout << "move constructor" << endl; 
} 

es kompiliert gut, aber Programm ist hinzufügen Ausgabe ist nur

construct from int 

So weit ich verstehe, fragt der Compiler nach dem Konstruktor, verwendet ihn aber nicht. Warum? Das ergibt für mich keinen Sinn.

P.S. Ich gehe davon aus, dass

A a = 0; 

Vorbehalte, von

ist
A a = A(0); 

aber warum weder bewegen noch Konstruktor verschieben Zuweisungsoperator genannt wird?

+0

Welche Compiler verwenden Sie? – Brotcrunsher

+2

Dies wurde in C++ 17 geändert (der Konstruktor für gelöschte Bewegungen kompiliert jetzt), aber das Kopieren/Verschieben von Elision war immer eine Sache davor. – chris

+0

Ich versuchte es auf g ++ 4.9, g ++ 6.3 und auf 5.0 alle gleich. (-O0 -std = C++ 11) –

Antwort

3

Nach dem C++ Standard (12.8 Kopieren und Verschieben von Klassenobjekten)

31 When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.122 This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies): .... — when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

und

30 A program is ill-formed if the copy/move constructor or the copy/move assignment operator for an object is implicitly odr-used and the special member function is not accessible (Clause 11). [ Note: Copying/moving one object into another using the copy/move constructor or the copy/move assignment operator does not change the layout or size of either object. —end note ]

+0

Ich finde es sehr schwierig, den Standard zu verstehen, können Sie etwas Erklärung oder Beispielcode geben? –

+0

@ HảiPhạmLê Es genügt, den fett gedruckten Text zu lesen. Und ein Beispielcode ist in der Frage angegeben. –

Verwandte Themen