Rules for return by value: when is a copy made?

Returning a local variable by value does not seem to involve the copying of that variable.

My 1st question is:
is this always the case or is this a type of context/compiler specific optimization?

(By using a test class with constructors that each report their identity, I see that the copy constructor is indeed not called when returning a local instance of that class)

My 2nd question is:
If in such situations a copy is sometimes made, then shouldn't it be impossible to return a local unique pointer by value?

Specifically, the following should not work b/c the statement "return local_ptr;" may try to make a copy of local_ptr, which should generate an error. However, the source material appears to reaffirm that no such copies will ever be made (source: http://www.umich.edu/~eecs381/handouts/C++11_smart_ptrs.pdf , p13-14).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

//create a Thing and return a unique_ptr to it:
unique_ptr<Thing> create_Thing()
{
unique_ptr<Thing> local_ptr(new Thing);
return local_ptr; // local_ptr will surrender ownership
}

//I have no questions about the following portion
//I only don't understand why "return local_ptr;" above should be valid 
//-cspace

void foo()
{
unique_ptr<Thing> p1(create_Thing()); // move ctor from returned rvalue

// p1 now owns the Thing
unique_ptr<Thing> p2; // default ctor'd; owns nothing
p2 = create_Thing(); // move assignment from returned rvalue
// p2 now owns the second Thing
}

I've always thought that return by value should make a copy because the local variable will be out of scope.
Last edited on
> Returning a local variable by value does not seem to involve the copying of that variable.

Copy elision: http://en.cppreference.com/w/cpp/language/copy_elision


> is this always the case or is this a type of context/compiler specific optimization?

Every mainstream C++ compiler implements copy elision. It is allowed by the standard, but it’s not mandatory.


> shouldn't it be impossible to return a local unique pointer by value?

std::unique_ptr<> is MoveConstructible.
A copy or move operation associated with a return statement may be elided or considered as an rvalue for the purpose of overload resolution in selecting a constructor - IS
Thanks very much.
Topic archived. No new replies allowed.