Chapter 4. The Curious Untemporary Reference

 

Be yourself; everybody else is already taken.

 
 --Sarah Leunde

A little-known feature of C++ impacts the semantics of code that makes use of by-value temporary element references (Section 3.3). Consider the following code:

std::string const& rs = std::string("Is it safe? Zzzz");
std::cout << rs << std::endl;

If your first instinct is to declare the code ill defined and the use of the reference rs in the output statement likely to crash the process, consider yourself reasonable but wrong. This is not so. C++ requires that references to instances of class type be valid until the end of their scope of declaration (C++-03: 8.5.3;5, 12.2;3), which may be achieved by creating a hidden temporary referent (Section ...

Get Extended STL, Volume 1: Collections and Iterators now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.