dem*_*orz 10 c++ lambda move-semantics c++11 c++14
我有以下测试代码:
#include <iostream>
#include <string>
void printValue(std::string&& val)
{
std::cout << "Got value: " << val << "\n";
}
int main() {
std::string testValue = "Test Value";
auto lambda = [testValue = std::move(testValue)]() mutable
{
printValue(std::move(testValue));
};
lambda();
lambda();
lambda();
}
Run Code Online (Sandbox Code Playgroud)
我得到了结果:
Got value: Test Value
Got value: Test Value
Got value: Test Value
Run Code Online (Sandbox Code Playgroud)
它是一个有效的假设,从已经移动捕获的lambda中移动一个对象将始终具有它被移动到lambda中的初始状态,或者这只是一个对象处于"有效但未指定状态"的工件?
son*_*yao 21
std::move不执行移动操作; 它只是将参数转换为右值.对于您的代码,printValue通过rvalue-reference获取参数,因此参数testValue将通过引用传递.但是没有对它执行移动操作,那么testValue就不会改变.
如果更改val为按值传递,则参数testValue将被移入val,或者您可以显式添加移动操作
void printValue(std::string&& val)
{
std::cout << "Got value: " << val << "\n";
std::string x = std::move(val); // perform move operation on val
}
Run Code Online (Sandbox Code Playgroud)
两者都会导致移动操作执行3次,然后你会得到不同的结果,例如使用clang,
Got value: Test Value
Got value:
Got value:
Run Code Online (Sandbox Code Playgroud)
PS:正如你所说,在从对象移动构造之后,将保持有效但未指定的状态.标准不保证上述行为,尽管大多数实现都这样做.