gpt4 book ai didi

c++ - "placement new"有什么用?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:44:45 27 4
gpt4 key购买 nike

这里有人用过C++的“placement new”吗?如果是这样,为什么?在我看来它只对内存映射硬件有用。

最佳答案

Placement new 允许您在已分配的内存中构造一个对象。

当您需要构造一个对象的多个实例时,您可能希望这样做以进行优化,而且每次需要一个新实例时不重新分配内存会更快。相反,为可以容纳多个对象的内存块执行一次分配可能会更有效,即使您不想一次使用所有对象也是如此。

DevX 给出一个 good example :

Standard C++ also supports placementnew operator, which constructs anobject on a pre-allocated buffer. Thisis useful when building a memory pool,a garbage collector or simply whenperformance and exception safety areparamount (there's no danger ofallocation failure since the memoryhas already been allocated, andconstructing an object on apre-allocated buffer takes less time):

char *buf  = new char[sizeof(string)]; // pre-allocated buffer
string *p = new (buf) string("hi"); // placement new
string *q = new string("hi"); // ordinary heap allocation

您可能还想确保关键代码的某个部分不会出现分配失败(例如,在起搏器执行的代码中)。在这种情况下,您可能希望更早地分配内存,然后在临界区内使用 placement new。

在 placement new 中释放

你不应该释放每个使用内存缓冲区的对象。相反,您应该只删除 [] 原始缓冲区。然后您将不得不手动调用类的析构函数。有关这方面的好的建议,请参阅 Stroustrup 的常见问题解答:Is there a "placement delete"

关于c++ - "placement new"有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41201090/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com