Naseeb Panghal
Naseeb Panghal

Reputation: 159

why temporary object gets created while returning by value not while passing by value to function parameter

Prototypes:

class A;
A func(A obj2)
{
  return obj2;
};

int main()
{
  A obj1;
  A obj3 = func(obj1);

  return 0;
}

While passing arguments to a function by value, it is copied from calling function's stack variable(obj1) to called function's stack variable(obj2), without any temporary object. Then why can't it be same way while returning by value from the function. i.e obj2 can be copied to obj3 directly without creating any temporary object(Forget RVO here).

Is it because func() can be called without collecting its return value? or there some other logic behind the scene?

Upvotes: 1

Views: 126

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473447

Pre-C++17, things work as they do because that was the model the language set down. A prvalue represented a temporary object. If a function is to return a prvalue, then the return statement must create that temporary object using the expression it is given. That necessarily involves a copy/move operation. The assignment of the prvalue into an object being initialized will perform a copy/move from the temporary into the new object.

Note that C++17 provided guaranteed elision by essentially redefining what a prvalue is. It is no longer an object; it is an initializer for an object. Which object gets initialized depends on how the prvalue gets used. The return statement doesn't create a temporary; its expression simply defines what the initializer will be. If you use the prvalue to initialize an object of the prvalue's type, then it initializes that object. If you try to initialize an object of some other type, then a temporary of the prvalue's type is initialized, and the other object is initialized through that temporary.

Upvotes: 3

Related Questions