Chapter 40. Object Lifetimes—Part 1

Difficulty: 5

“To be, or not to be…” When does an object actually exist? This problem considers when an object is safe to use.

Critique the following code fragment.

void f() 
{
  T t(1);
  T& rt = t;
  //--- #1: do something with t or rt ---
  t.~T();
  new (&t) T(2);
  //--- #2: do something with t or rt ---
}// t is destroyed again

Is the code in block #2 safe and/or legal? Explain.

Solution

Solution

Yes, #2 is safe and legal (if you get to it), but:

  • The function as a whole is not safe.

  • It's a bad habit to get into.

The C++ standard explicitly allows this code. The reference rt is not invalidated by the in-place destruction and reconstruction. ...

Get Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.