gpt4 book ai didi

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

转载 作者:bug小助手 更新时间:2023-10-28 01:31:14 28 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

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

新展示位置的分配

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

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

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