Reference Bug in C++?

Hi,

Isn't there a bug here in the code?

returnarg receives a temporary object which is destructed after the function is returned.

i.e. r1's address is not valid after the function terminates.

However, r still aliases r1's address.

Isn't it a bug?

If it is, how can you overcome it if you want your function to return a reference?

1
2
3
4
5
6
7
8
9
10
11
12
const Rectangle& returnarg(const Rectangle& r1)
{
	return r1;
}

int main()
{
	const Rectangle& r = returnarg(Rectangle(2, 3, 4, 5, 6));
	cout << r.getArea();

        return 0;
}


Last edited on
While const references extend the lifetimes of nameless temporary objects, they cannot "pass it on" (the object is no longer nameless).
So yes, this program has a bug: r is a dangling reference by the time getArea() is called.

If you must handle rvalues, you could provide an rvalue overload, but it wouldn't be able to return a reference:
1
2
3
4
Rectangle returnarg(Rectangle&& r1)
{
        return std::move(r1);
}
I'm not sure if it applies to this case, but const reference like on line 8 can extend the lifetime of a temporary. If the temporary is actually destructed though then it is undefined behavior to use it - why not print the destructor calls?
Cubbi +1

This case is specifically mentioned as one of the exceptions to
The temporary to which the reference is bound <elided> persists for the lifetime of the reference except: ....

(one of the exceptions:) A temporary bound to a reference parameter in a function call persists until the completion of the full-expression containing the call.


> why not print the destructor calls?

http://coliru.stacked-crooked.com/a/8b3ecb7ba5792a9e
Last edited on
@ L B
I printed the destructor, which indeed was called for r1 after returning from the function.

So as Cubbi said, r is dangling object.


@ Cubbi

I've never seen anyone use double && before.

thanks.


So actually, every function that returns reference of the argument that it receives, has this potential bug.
Topic archived. No new replies allowed.