Is it well-defined/legal to placement-new multiple times at the same address?

前端 未结 3 1947
滥情空心
滥情空心 2021-02-19 11:25

(Note: this question was motivated by trying to come up with preprocessor hackery to generate a no-op allocation to answer this other question:

Macro that accept new

3条回答
  •  一整个雨季
    2021-02-19 11:48

    foo* p1 = new (buffer) foo(1);
    foo* p2 = new (buffer) foo(2);
    p1->~foo();
    p2->~foo();
    

    You are destructing the same object twice, and that alone is undefined behavior. Your implementation may decide to order a pizza when you do that, and it would still be on the right side of the spec.

    Then there is the fact that your buffer may not be properly aligned to emplace an object of type foo, which is again non standard C++ (according to C++03, I think C++11 relaxes this).

    Update: Regarding the question specified in the title,

    Is it well-defined/legal to placement-new multiple times at the same address?

    Yes, is it well-defined to placement-new multiple times at the same address, provided that it points to raw memory.

提交回复
热议问题