【发布时间】:2017-01-07 08:18:18
【问题描述】:
#include <string>
#include <vector>
using namespace std;
auto f()
{
vector<string> coll{ "hello" };
//
// Must I use move(coll[0]) ?
//
return coll[0];
}
int main()
{
auto s = f();
DoSomething(s);
}
我知道:如果我只是return coll;,那么coll 肯定会在返回时被移动。
但是,我不确定:coll[0] 是否也保证在返回时被移动?
更新:
#include <iostream>
struct A
{
A() { std::cout << "constructed\n"; }
A(const A&) { std::cout << "copy-constructed\n"; }
A(A&&) { std::cout << "move-constructed\n"; }
~A() { std::cout << "destructed\n"; }
};
struct B
{
A a;
};
A f()
{
B b;
return b.a;
}
int main()
{
f();
}
gcc 6.2 和 clang 3.8 输出相同:
构造
复制构造
破坏
破坏
【问题讨论】:
-
"那么
coll保证在返回时被移动。"不,不是。副本可能会被省略,在这种情况下,没有移动。 -
你没有使用 f() 的返回值,有什么要移动的?
-
并且可以移动左值的条件与复制省略密切相关(请参阅我的答案。)
标签: c++ c++11 standards move-semantics