Hector
Hector

Reputation: 2534

Unexpected behavior of reference to const temporary object

The following code compiles in Visual Studio 2013 without any warnings. Removing the comment in the last line will not compile. Is this a bug in Visual Studio 2013? If not, how am I supposed to understand it within the standard?

I think that allowing to take the reference of a temporary object is something very dangerous, isn't it?

struct A
{
    string a;

    void f( const string & toMove )
    {
        a = toMove;
    }
    void g( string & toMove )
    {
        a = toMove;
    }
} aa;

stringstream d_SS;
d_SS << "A string";
aa.f( d_SS.str() );
//aa.g( d_SS.str() );

Edit

In this related question, they explain that one is 'not allowed to get non-const reference to a temporary object'. My question would be then why we are allowed to get const references to temporary objects in the way aa.f( d_SS.str() ) does. d_SS.str() is dead before it enters to the body of function!

Upvotes: 0

Views: 61

Answers (1)

M.M
M.M

Reputation: 141534

d_SS.str() is dead before it enters to the body of function!

Not true; it is still alive until the end of the current full-expression , which in this case is the semicolon at the end of aa.f( d_SS.str() ); .

There is only danger if aa.f takes a reference or pointer to its argument and saves that to some external data area. It's completely safe for aa.f to just read its argument.

Upvotes: 1

Related Questions