4

Well, I know this sounds pure evil. I was reading this SO post and stumbled upon the technique of reconstructing a stack object. The basic idea is:

{
    T obj(...);  // dtor will be called at end of scope
    obj.~T();    // YOLO

    new (&obj) T(...);
    // obj goes out of scope. The compiler inserts `obj.~T();` here.
}

...so that we can reuse the same chunk of memory for as many times as we like. Is this code legal by the standard? Is craziness like this undefined behavior?

Community
  • 1
  • 1
Zizheng Tai
  • 6,170
  • 28
  • 79
  • What if constructor in placement new throw an exception? will you have an object that it's destructor call twice? – MRB Jan 14 '17 at 06:58
  • The standard library uses this "technique" all over the place, but it takes care of some other things like exception guarantees as @MRB mentioned. Things can go wrong. Don't do this. – DeiDei Jan 14 '17 at 07:03

1 Answers1

2

This construct applies placement new. See also. It is standard C++ since the first standard. It predates the first standard and was introduced to the core language because of its usefulness. So not "craziness" and naturally not UB per se. You might of course carelessly provoke UB or other memory bugs in a concrete application of placement new. As with all raw memory management facilities provided by the language, it is now best left to the implementors of the Standard Library and 3rd party libraries that prempt our need to wrangle with its risks.

Community
  • 1
  • 1
Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182