(N)RVO helps to avoid unnecessary copying and creating of temporary objects when the return value is being assigned into a new variable (thus avoiding the copy constructor).
So something like this should be optimized by RVO:
MyObj getMyObj() {
return MyObj();
}
MyObj myobj = getMyObj();
However, will it also happen when the call site object already exists? (I.e. in the case where the =
operator is used instead of the copy constructor). I tried to find literature about this but (N)RVO seems to be always described in terms of avoiding the copy constructor. Not sure if it is actually safe to modify the call site object in this case.
MyObj myobj;
//will getMyObj() first create a temporary object and then copy it via the = operator?
myobj = getMyObj();