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