Reputation: 866
I'm wondering why returning const reference
of a local object is illegal whereas returning a local object
is legal as long as you assign it to a const reference
?
vector<int> f_legal() {
vector<int> tempVec;
tempVec.push_back(1);
return tempVec;
}
const vector<int>& f_illegal() {
vector<int> tempVec;
tempVec.push_back(1);
return tempVec;
}
void g() {
const vector<int>& v1 = f_legal(); // legal
const vector<int>& v2 = f_illegal(); // illegal
}
Edit: My point is that if assigning a const ref to a returned local variable is legal, then shouldn't assigning a const ref to a returned const ref of a local variable be legal as well?
Upvotes: 13
Views: 10152
Reputation: 172924
Even if you assign it to a const reference, the return value is declared as passed by value, that means it'll be copied[1] to outside as a temporary object, and then binded to the const reference. Binding temporary object to a const reference is fine, the object won't be destroyed until getting out of the lifetime of the const reference.
On the other hand, returning reference of a local variable is illegel. The local variable'll be destroyed when the function returned, that means the outside reference will be dangled.
EDIT
My point is that if assigning a const ref to a returned local variable is legal, then shouldn't assigning a const ref to a returned const ref of a local variable be legal as well?
The point is the 1st case is not assigning a const ref to a returned local variable, it's assigning a const ref to a returned temporary variable. (Which might copied from the local variable.)
[1] The copy might be omitted according to RVO technically.
Upvotes: 14
Reputation: 40859
Most likely because it would totally ruin the whole stack based calling conventions that have served us well for decades...that pretty much every CPU assumes.
Upvotes: 1
Reputation: 75707
Returning a reference to a local variable is illegal (Undefined Behavior). Period. There is no const
or mutable
clause.
This is because local function variables have automatic storage duration. They are "destroyed" after the function exits. If the function returns a reference to such a variable, that reference it is said to be dangling: it refers to an object that no longer exists.
The first one is legal because of a special C++ rule: initializing a reference to a prvalue
extends the lifetime of that temporary object to the lifetime of the reference.
Upvotes: 15