How could I sensibly overload placement operator new?

后端 未结 9 2010
北恋
北恋 2020-12-05 23:49

C++ allows overloading operator new - both global and per-class - usual operator new, operator new[] used with new[] stat

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 00:20

    The most important extra-functionality for placement new overload would be to check address alignment.

    For example, lets assume some class requires 16-bytes alignment. Developer overloads new, new[], delete and delete[] - just to be sure everything is aligned properly.

    Everything works fine to the moment when he tries to use his class with library which uses placement new... Library has no idea if/what alignment is required for the class and address it tries to "place" the object to might not be aligned - big boom.

    The simplest example of such situation - try using std::vector where T requires non-standard alignment.

    Overload for placement new allows to detect if pointer is not aligned - might save hours of debugging.

提交回复
热议问题