O'Reilly logo

Extended STL, Volume 1: Collections and Iterators by Matthew Wilson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required