下面的代碼,在VS2013編譯,從未調用的std :: string的移動構造函數(通過設置斷點檢查,const的裁判拷貝構造函數,而不是調用。爲什麼下面的代碼不會調用std :: string的移動構造函數?
#include <iostream>
#include <string>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
struct foo
{
foo(std::string& str1, std::string& str2) : _str1(str1), _str2(str2) {}
~foo() { std::cout << "Either \"" << _str1 << "\" or \"" << _str2 << "\" was returned." << std::endl; }
std::string& _str1;
std::string& _str2;
};
std::string foobar()
{
std::string str1("Hello, World!");
std::string str2("Goodbye, cruel World.");
foo f(str1, str2);
srand(time(NULL));
return (rand() % 2) ? str1 : str2;
}
int main()
{
std::cout << "\"" << foobar() << "\" was actually returned." << std::endl;
return EXIT_SUCCESS;
}
我希望在foobar的return語句()以調用移動構造函數,因爲我返回一個本地(蘭德()是爲了防止NRVO),就像問題的回答,如Returning std::move of a local variable
這是我試圖添加另一個例子我的其他問題在這裏:https://softwareengineering.stackexchange.com/questions/258238/move-semantics-in-c-move-return-of-local-variables
是否使用移動的構造函數,如果你刪除'foo'變量定義?我猜想編譯器足夠聰明,知道你已經參考了使得移動無效的字符串(再次,猜測)。 – uesp 2014-10-07 18:16:53
不,它仍然使用複製構造函數,如果我這樣做。 – Bwmat 2014-10-07 18:18:53
返回的「首先嚐試右值」僅適用於「如果複製elision條件已滿足或將滿足,除了源對象是函數參數」這一事實。在C++ 14中,它擴展到所有return語句直接命名本地對象的情況。 (見[這個答案](http://stackoverflow.com/questions/25875596/can-returning-a-local-variable-by-value-in-c11-14-result-in-the-return-value-b/25876175#25876175)從標準的完整報價。)您的條件表達式既不是。 – 2014-10-07 18:18:53