Friday, 6 September 2013

How does this work with Return Value Optimization?

How does this work with Return Value Optimization?

vector<int> f(const vector<int>& v)
{
vector<int> ret(v.size());
fill(ret.begin(), ret.end(), 123);
copy(v.begin(), v.end(), ret.begin());
return ret;
}
int main()
{
vector<int> v(10);
v = f(v);
}
If return value optimization is applied to f, then the local variable ret
shares the same address as v in main. But if this is true, filling ret
will trash the data in v before the copy. The code is correct without RVO
and optimizations shouldn't break behavior.
Is this safe or do I not understand RVO correctly?

No comments:

Post a Comment