Is it UB to re-use an object's storage without destroying it first?

前端 未结 1 1132
栀梦
栀梦 2021-02-05 11:13

Given non-POD type T:

auto p = new T();
::new (p) T();
/* ... */
delete p;

This is UB, right?

Clearly I\'m not directly le

1条回答
  •  逝去的感伤
    2021-02-05 11:47

    It rather depends.

    [C++11: 3.8/1]: The lifetime of an object of type T ends when:

    • if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
    • the storage which the object occupies is reused or released.

    Clearly, this is a case of re-use.

    And:

    [C++11: 3.8/4]: A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.

    So, even for a non-POD type T, it's valid iff nothing in your program actually relied on what the destructor was doing.

    It's a bit airy-fairy, but it does potentially allow what you're doing.


    Note that this leniency does not extend to some only slightly more bizarre cases:

    [C++11: 3.8/9]: Creating a new object at the storage location that a const object with static, thread, or automatic storage duration occupies or, at the storage location that such a const object used to occupy before its lifetime ended results in undefined behavior

    0 讨论(0)
提交回复
热议问题