Boost logo

Boost :

From: Bryan Ross (bross_at_[hidden])
Date: 2002-09-04 15:12:18


I may not be understanding something here, but are you saying that the
following code won't work?

#include <iostream>
#include <string>
using namespace std;
struct hold
{
        hold(const int& i) : x(i) {}
        const int& x;
};
int f()
{
        return 3;
}
int main(int argc,char** argv)
{
        hold* h = new hold(f());
        cout << h->x << endl;
        delete h;
        return 0;
}

This compiles and outputs '3', as expected. However, if I change int f()
to const int& f(), I get a warning about returning the address of a
temporary variable (using MSVC++ 7)

Bryan Ross
bross_at_[hidden]

-----Original Message-----
From: David Abrahams [mailto:dave_at_[hidden]]
Sent: Wednesday, September 04, 2002 12:51 PM
To: boost_at_[hidden]
Subject: Re: [boost] safe_dereference()

From: "Thomas Wenisch" <twenisch_at_[hidden]>

> This is incorrect. The code returns a *const* reference to the
> temporary. This extends the life of the temporary to the life of the
> reference.

Yes, but that reference is created within the function. There's another
reference on the outside of the function. By your logic, the temporary
would live forever in this code:

int f();
struct hold { hold(int const& x_) : x(x_) {} int const& x; }
hold* h = new hold(f());

But it doesn't work that way.

-----------------------------------------------------------
           David Abrahams * Boost Consulting dave_at_[hidden] *
http://www.boost-consulting.com

_______________________________________________
Unsubscribe & other changes:
http://lists.boost.org/mailman/listinfo.cgi/boost


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