0

The Standard said that move constructor was applicable when function returns a value. Its not quite clear, because I thought when function returns a value, it creates a temporary object being constructed while function was executing. Of course, move constructor can be elided in order of the copy-elision process. But I'd like to consider the case where it doesn't:

#include <iostream>

struct X
{
    int a = 42;
    X();
    X(const X&&, int t = 24);
};

X::X(){ }

X::X(const X&&, int g)
{
    std::cout << g << std::endl;
}

X foo()
{
    return X();
}

int main()
{
    foo(); //move-constructor called
}

If we have a function, say

int foo()
{ 
    int a = 5; 
    return a; 
}

What actually happens within the memory when a function returns a value? Are there significant differences between the first and the second examples?

  • 1
    `when function returns a value, it creates a temporary object`. Quite. Said object may be initialized using a move constructor. Where's the contradiction? – Igor Tandetnik Nov 10 '14 at 04:57
  • Note that return value optimization (RVO) can elide the copy/move of the temporary by having the function that returns the object construct it directly where it will be returned to. – cdhowie Nov 10 '14 at 05:00
  • The significant difference between the first and second example is that in the first case, the move constructor has a side effect and you can observe it being called. In the second case, copying of an int doesn't produce any observable side effects. I suppose I don't quite understand the question. – Igor Tandetnik Nov 10 '14 at 05:00
  • "What actually happens within the memory when a function returns a value?" - there's not necessarily anything happening "within the memory", for many cases the result will be expected in a specific CPU register. That's what your `int foo() { int a = 5; return a; }` function will likely do if any optimisation is applied - load the immediate value 5 into the accumulator CPU register. – Tony Delroy Nov 10 '14 at 05:10
  • this link may help - http://stackoverflow.com/questions/665781/copy-constructor-in-c-is-called-when-object-is-returned-from-a-function – Harpreet Singh Nov 10 '14 at 05:19

0 Answers0