移動セマンティクスが有効になっている「全体」オブジェクトが、次のように関数から返される場合を考えてみますstd::basic_string<>
。
std::wstring build_report() const
{
std::wstring report;
...
return report;
}
次に、返された文字列を移動セマンティクスで使用するかどうかを「最良の」選択にすることが現実的に期待できますか。
const std::wstring report(std::move(build_report()));
または、(N)RVOを使用して実行する必要がある場合
const std::wstring report(build_report());
または、const参照を一時的なものにバインドすることもできます
const std::wstring& report(build_report());
もしあれば、これらのオプションを決定論的に選択するためにどのようなスキームがありますか?
編集1:上記の使用法はstd::wstring
、移動セマンティクスが有効なタイプの単なる例であることに注意してください。それはあなたと交換することもできますarbitrary_large_structure
。:-)
編集2:次のVS 2010で速度最適化リリースビルドを実行するときに、生成されたアセンブリを確認しました。
std::wstring build_report(const std::wstring& title, const std::wstring& content)
{
std::wstring report;
report.append(title);
report.append(content);
return report;
}
const std::wstring title1(L"title1");
const std::wstring content1(L"content1");
const std::wstring title2(L"title2");
const std::wstring content2(L"content2");
const std::wstring title3(L"title3");
const std::wstring content3(L"content3");
int _tmain(int argc, _TCHAR* argv[])
{
const std::wstring report1(std::move(build_report(title1, content1)));
const std::wstring report2(build_report(title2, content2));
const std::wstring& report3(build_report(title3, content3));
...
return 0;
}
2つの最も興味深い結果:
- 明示的にmoveコンストラクターの使用を要求
std::move
すると、命令数が3倍になります。report1
- 以下の回答で
report2
JamesMcNellisが指摘しているように、report3
実際には、明示的に呼び出すよりも3分の1の命令で同一のアセンブリを生成しstd::move
ます。