0

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!

Community
  • 1
  • 1
Hector
  • 2,464
  • 3
  • 19
  • 34
  • I don't understand what the issue is that you're having here. One takes a `const` reference, so passing a temporary to such function is perfectly ok since the function can't change the parameter anyway. – PaulMcKenzie Nov 09 '14 at 07:23
  • @PaulMcKenzie: In my understanding, being constant and being temporary are not the same thing and they do not imply each other. My comment to ravi's answer suggests that d_SS.str() is not constant since you can modify it. – Hector Nov 09 '14 at 07:39
  • Are you asking why `aa.f( d_SS.str() );` does not give an error? – M.M Nov 09 '14 at 07:43

1 Answers1

1

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • Thank you. For reference, I found this other [related question](http://stackoverflow.com/a/2784304/2549876). Just to be explicit: "allowing to take the reference of a temporary object is something very dangerous, isn't it?" is answered as: No, if it is a const reference because it will prolong the life of the object until the semicolon. – Hector Nov 09 '14 at 08:16