简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM