2017-10-14 27 views
6

この理由:明示的に削除された移動コンストラクタ

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

そして、私はそのような動きのコンストラクタを追加するとき

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

それがうまくコンパイルが、なぜプログラムの開発年代:

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

    A(A&&) = delete; 

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

int main(){ 
    A a = 0; 
} 

は私にエラーを与えます出力はちょうど

です

私が理解する限り、コンパイラはコンストラクタを要求しますが、それを使用しません。どうして?これは私には意味がありません。

P.S.私は

A a = 0; 

A a = A(0); 

のequvalentですが、なぜどちらも移動コンストラクタや移動代入演算子が呼び出される?と仮定しますか

+0

によると? – Brotcrunsher

+2

これはC++ 17で変更されました(削除された移動コンストラクタは現在コンパイルされています)。しかし、copy/move elisionは常に前のことでした。 – chris

+0

私はg ++ 4.9、g ++ 6.3、clang 5.0を試してみました。 (-O0 -std = C++ 11) –

答えて

3

あなたがコンパイラを使用しているC++標準(12.8コピーとクラスオブジェクトを移動する)

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

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

私はこのスタンダードを理解することは非常に難しいと思っています。説明やサンプルコードを教えてもらえますか? –

+0

@HảiPhạmLê太字のテキストを読むだけで十分です。そして、サンプルコードがその質問に与えられます。 –

関連する問題