让我们考虑这两个函数:
// 1. Multiple returns of the same named object
string f() {
string s;
if (something())
return s.assign(get_value1());
else
return s.assign(get_value2());
}
Run Code Online (Sandbox Code Playgroud)
和
// 2. Multiple returns, all of unnamed objects
string g() {
if (something())
return get_value1();
else
return get_value2();
}
Run Code Online (Sandbox Code Playgroud)
这些函数中的每一个函数在RVO方面的实际行为当然都与编译器有关.但是,我是否认为两者的RVO很常见?
ps(见答案)功能#1旨在如下:
string f() {
string s;
if (something())
return s;
s.assign(get_value());
return s;
}
Run Code Online (Sandbox Code Playgroud) 是否有一种干净的方式来移动它的元素?就像是:
set<A> s {...};
vector<A> v;
for (const A& a : s)
v.push_back(move(const_cast<A&>(a)));
s.clear(); //undefined behavior?
Run Code Online (Sandbox Code Playgroud)