Hi,
The current standard says (12.8, p. 31 and 32) that the copy/move from
an automatic object into a temporary returned by a function as well as
the copy/move from a temporary to an automatic object can be elided,
thus avoiding any copying/moving in the following example.
vecotr<string> generate()
{
vecotr<string> ans;
populate(ans);
return ans;
}
auto vec = generate();
The standard also says that this optimization is even allowed if copy/
move ctor or destructor have side effects. This somehow implies that
it is only constructor's or destructor's side effects that can affect
program's behaviour if elided. But how about the following case, if I
slightly change function generate():
vecotr<string> generate()
{
vecotr<string> ans;
populate(ans);
ScopeGuard g = [&]{ ans.clear(); }
return ans;
}
ScopeGuard woks such that it registers a callback in the constructor,
and calls the callback in the destructor. If copy elision is not
performed, the additional call to function clear() has no impact on
the program, because we are working on a local copy. However, if the
copies are elided, the auto variable 'ans' inside the function, and a
temporary, and the initialized global variable 'vec' are to be treated
as the same object. In this case, if I interpret the standard
correctly, the value of global 'vec' will be cleared. This would not
have been the case if the moves were not elided. Thus, copy elision
may change program behaviour even if constructors and destructors have
no side effects.
Now, to my questions.
1. Is my interpretation of the standard correct?
2. Is this behaviour intended?
Regards,
&rzej
--
[ See
http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]