Is it legal to use placement new on initialised memory?

后端 未结 3 2081
独厮守ぢ
独厮守ぢ 2020-12-11 02:59

I am exploring the possibility of implementing true (partially) immutable data structures in C++. As C++ does not seem to distinguish between a variable and the object that

3条回答
  •  半阙折子戏
    2020-12-11 03:23

    From the C++ standard draft N4296:

    3.8 Object lifetime
    [...]
    The lifetime of an object of type T ends when:
    (1.3) — if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
    (1.4) — the storage which the object occupies is reused or released.
    [...]
    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 yes, you can end the lifetime of an object by reusing its memory, even of one with non-trivial destructor, as long as you don't depend on the side effects of the destructor call.

    This applies when you have non-const instances of objects like struct ImmutableBounds { const void* start; const void* end; }

提交回复
热议问题