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

前端 未结 3 1935
滥情空心
滥情空心 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:52

    No - this doesn't look right.

    When you use placement new, the object will be constructed at the address you pass. In this example you're passing the same address (i.e. &buffer[0]) twice, so the second object is just obliterating the first object that's already been constructed at this location.

    EDIT: I don't think I understand what you're trying to do.

    If you have a general object type (that may have non-trivial ctor/dtor's that might allocate/deallocate resources) and you obliterate the first object by placement new'ing over the top of it without first explicitly calling it's destructor, this will at least be a memory leak.

提交回复
热议问题