次のプログラムを検討してください。
#include<iostream>
using namespace std;
struct S
{
S() = default;
S(const S& other) = delete;
S(S&& other) = delete;
int i;
};
S nakedBrace()
{
return {}; // no S constructed here?
}
S typedBrace()
{
return S{};
}
int main()
{
// produce an observable effect.
cout << nakedBrace().i << endl; // ok
cout << typedBrace().i << endl; // error: deleted move ctor
}
サンプル セッション:
$ g++ -Wall -std=c++14 -o no-copy-ctor no-copy-ctor.cpp
no-copy-ctor.cpp: In function 'S typedBrace()':
no-copy-ctor.cpp:19:12: error: use of deleted function 'S::S(S&&)'
return S{};
^
no-copy-ctor.cpp:8:5: note: declared here
S(S&& other) = delete;
gcc が を受け入れることに驚きましたnakedBrace()
。概念的には、2 つの関数は同等であると考えました。一時的な関数がS
構築されて返されます。コピー省略は実行される場合と実行されない場合がありますが、標準 (12.8/32) で義務付けられているように、move または copy ctor (両方ともここで削除されます) は引き続きアクセス可能でなければなりません。
nakedBrace()
それは決して S を構築しないということですか? それとも、コピーの移動/ctorが概念的に必要ないように、ブレースの初期化を使用して戻り値に直接入力しますか?