J. *_*Doe 2 c++ language-lawyer c++11
可能是一个蹩脚的问题,但我一直没有找到全面的答案.
参数std::vector::emplace_back是r值引用.据我所知,在通过r值引用传递对象后使用对象是不安全的.我的意思是:
std::string str("hello world");
std::string str2(std::move(str)); // string::string(string &&);
cout << str; // unsafe, str was moved to str2
Run Code Online (Sandbox Code Playgroud)
那么,下面的例子会发生什么?
std::vector<std::string> array;
std::string str("hello world"); // what if add 'const' qualifier here?
array.emplace_back(str); // template <class... Args>
// void emplace_back (Args&&... args);
std::cout << str; // safe or not? str was moved or copied?
Run Code Online (Sandbox Code Playgroud)
我真的很困惑.我的测试表明,str之后使用是安全的emplace_back,但是我的(破碎?)逻辑告诉我str移动了,之后不应该使用它.
PS.对不起,我的英语不好 :)
emplace-style函数的参数是转发引用,这意味着它们成为左值参数的左值引用和rvalue参数的右值引用.
同
array.emplace_back(str);
Run Code Online (Sandbox Code Playgroud)
str是一个左值(你还没有将它转换为右值std::move),因此它将被复制.它将在通话后保留其价值.