Boost logo

Boost :

From: Eric Niebler (eric_at_[hidden])
Date: 2006-02-11 21:05:15


Vertleyb wrote:

>
> #include <iostream>
> using namespace std;
>
> const int f()
> {
> return 0;
> }
> const int& ff()
> {
> const int& result = f();
> return result;
> }
> int main()
> {
> const int& r = ff();
> cout << r << endl;
> return 0;
> }
>
> I am still not sure though, if the lifetime is extended far enough for this case, or does this just work correctly by accident...
> (have to take a closer look into the Standard)
>

This is broken. f() returns a temporary, which is bound to a const ref
and has its lifetime extended to the end of the scope containing the
const ref. So when ff() returns, the temporary object will be cleaned
up, so ff() is returning a dead reference. If you use an object with a
destructor instead of int, you can set a breakpoint to verify.

-- 
Eric Niebler
Boost Consulting
www.boost-consulting.com

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk