Why getting a value from a function using auto&& seems to produce a temporary value

I have the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int&& getInt()
{
	return 4;
}

int& getLvalueInt()
{
	int r = 5;
	return r;
}

int main()
{
	auto&& ex = getInt();
	++ex;
	auto& exx = getLvalueInt();
	++exx;
}


In this code, getInt() returns 4 into ex and ++ex increases ex to 5 as expected. However when getLvalueInt() is called, ex is overwritten with trash. Why?


Thanks
Juan
Both functions return dangling references.
Last edited on
Then, why can we change the following vector if the auto&& are dangling references?

1
2
3
4
	std::vector<bool> qq{ true, false, true, false };
	for (auto&& elt : qq) { 
             elt = true;
        }


Typical implementations of vector<bool>::iterator::operator* return values of type vector<bool>::reference rather than references of type bool&, as might be expected.
https://en.cppreference.com/w/cpp/container/vector_bool/reference

Naturally it's impossible to return a dangling reference if no reference type is returned.

The trick with returning reference types is to ensure that the referent is still within its lifetime when the function ends. Returning a reference to a local variable just always returns a dangling reference because the local variable is destroyed at the end of the function. There is no way to extend the referent's life from the call-site.
Last edited on
Correction:

2
3
4
for (auto& elt : qq) {
    elt = true;
}

It might be worth reading up on lvalue references and move semantics.
An lvalue reference won't bind to an rvalue, which is a problem in this case.

This prior thread sheds some light:
http://www.cplusplus.com/forum/general/264257/
Last edited on
Topic archived. No new replies allowed.