1

即使您无法替换全局版本,也可以提供特定于类的位置新版本。类应该提供自己的placement new 运算符的情况有哪些?

即使我的班级没有实现放置 new,以下代码也可以工作(假设 abc 没有重载 operator new)。

char arr[100];

abc *pt = new(&arr)abc; 

所以我解释说,有一些默认放置 new 但是对于类,我们可以提供我们自己的 operator new 版本,我的问题是它的用例是什么?除了返回传递的相同指针之外应该做什么?您是否遇到过任何有用的示例/场景?

4

4 回答 4

1

Sounds like a quiz question...

Faster and Leaner Allocation
The most common reason is a lot of small objects that need to be allocated dynamically. A custom allocator for fixed-size objects has much less allocation overhead than a generic allocator, does not suffer from fragmentation, and is typically faster. (Also, when these allocations are removed from the main heap, they don't contribute to main heap fragmentation anymore).

Similary, a non-freeing allocator (where you can allocate multiple objects, but can't free them together, only in conjunction) is the fastest allocation scheme possible, and does not have any overhead (except alignment in a few rare cases). It makes sense if you are building a data structure that you never modify, only delete as a whole.

Other base allocator
Another application is allocating from a different heap than the C++ heap. Maybe the data in the objects needs to be allocated in shared memory for exchange with other processes, or it needs to be passed to a system function that takes ownership and requries the use of a certain allocator. (Note that this requires to implement the same mechanism for all sub-objects, too, there is no generic way to achieve that).

Similary (where I use it) is when you create code on the fly. Nowadays, you need to tell the OS that data on this memory page is allowed to run, but you get this memory in rather large chunks (e.g. 4K). So again, request a page (4K) from the OS with execution rights, then allocate many small objects on top of it - using placement new.

于 2009-08-27T06:38:40.520 回答
1

不幸的是,AFAIK,您不能对标准放置新运算符进行类特定的重载,只能对自定义放置新运算符进行重载。所以它的用例有点学术,但我想用它来禁止使用= deleteC++11 在类上放置新的。这适用于标准operator new,但不适用于新放置。

于 2015-09-19T11:37:23.790 回答
0

直接来自马口维基。标题为“使用”的部分强调了放置新位置的必要性。这里的这个 SO 线程也可能有帮助

更新: 专门回答你的问题;<new>如果您有一个要用于构造类的某些对象的内存池,但又不想为整个类重载 operator new,则可以使用 header 提供的标准放置 new 。在后一种情况下,所有类对象都按照类中定义的重载放置 new 放置

于 2009-08-27T05:59:46.433 回答
0

我不确定是否有可能超载新的位置,只有常规的新位置。我什至想不出一个单一的用途,因为唯一可能的实现只是创建一个临时对象并将它的 memcp'ing 到给定的内存地址 - 因为你不应该在那里分配任何其他内存,但是使用给定的。

于 2009-09-09T20:32:33.550 回答