Reference to an unnamed temporary object (lifetime)

After reading this answer from ildjarn , I wrote the following example, and it looks like an unnamed temporary object has the same lifetime as its link!

  • How is this possible?
  • Is it specified in the C ++ standard?
  • Which version?

Source:

#include <iostream> //cout #include <sstream> //ostringstream int main () { std::ostringstream oss; oss << 1234; std::string const& str = oss.str(); char const* ptr = str.c_str(); // Change the stream content oss << "_more_stuff_"; oss.str(""); //reset oss << "Beginning"; std::cout << oss.str() <<'\n'; // Fill the call stack // ... create many local variables, call functions... // Change again the stream content oss << "Again"; oss.str(""); //reset oss << "Next should be '1234': "; std::cout << oss.str() <<'\n'; // Check if the ptr is still unchanged std::cout << ptr << std::endl; } 

Execution:

 > g++ --version g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-54) Copyright (C) 2006 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. > g++ main.cpp -O3 > ./a.out Beginning Next should be '1234': 1234 
+3
c ++ reference temporary object-lifetime
source share
3 answers

How is this possible?

Because the standard says so, because it is considered useful. rvalue and const lvalue links extend the lifetime of temporary files:

[C++11: 12.2/5]: [..] Temporary link binding or temporary, which is the full object of the subobject to which the link is attached, is saved for the link lifetime, except [..]

and the exhaustive wording in [C++11: 8.5.3/5] requires that we do not bind temporary links to const lvalue links.


Is it specified in the C ++ standard? Which version?

Yes. All of them.

+9
source share

Temporary reference to a constant link extends the lifetime of a temporary link to the lifetime of a permanent link.

Good reading:

GotW # 88: Candidate for "Most Important Const"


Yes, this is stated in the C ++ standard from the moment the links were introduced.
Therefore, if you are wondering if this is a C ++ 11 function, it is not. It already exists in C ++ 03.

+6
source share

Ease of race in orbit . And I think this example will be more concise.

 #include <iostream> //cout #include <string> int main () { using namespace std; int a = 123; int b = 123; // int & a_b = a + b; // error! int const & a_b = a + b; cout<<"hello world!"<<endl; cout<<a_b<<endl; } 
+3
source share

All Articles