Search code examples
c++move

C++ how is it technically possible to move a function return value without a copy?


When a function returns a value, this is put on the stack (the function stack frames are deleted, but the return value remains there until the caller gets it).

If the return value is on the stack how can the move get that value without copying it in the variable memory location?

For example in this code:

A a = getA();

Solution

  • In many implementations of C++, a function returning a "complex" data type is passed a hidden parameter that is a pointer to the space where the returned instance is to reside. Essentially, the compiler turns Foo r = fun(); into

    char alignas(Foo) r[sizeof Foo]; // Foo-sized buffer, unitialized!
    fun(&r);
    

    As you can see, Foo is allocated on the stack in the caller's frame. Now, within the implementation of fun there could be a copy. The construction

    Foo fun() {
      Foo rv;
      ...
      return rv;
    }
    

    is generally implemented as

    void fun(Foo * $ret) {
      Foo rv;
      ..
      new ($ret) Foo(rv); // copy construction
    }
    

    When the return value optimizations are applied, this gets changed to

    void fun(Foo * $ret) {
      Foo & rv = *(new ($ret) Foo);
      ...
      return;
    }
    

    Now there's no copying involved. That's a mile-high overview of how an implementation might do it.