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

标签 c++ memory-management new-operator placement-new

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

最佳答案

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

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

DevX 给出一个 good example :

Standard C++ also supports placement new operator, which constructs an object on a pre-allocated buffer. This is useful when building a memory pool, a garbage collector or simply when performance and exception safety are paramount (there's no danger of allocation failure since the memory has already been allocated, and constructing an object on a pre-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/58019519/

相关文章:

c++ - 管理C++大型静态库

c++ - 无效指针处理策略

iphone - ARC 不释放实例变量

c++ - 删除数组c++崩溃问题

c++ - size_t 参数新运算符

c++ - 使用具有不同编译器版本的 boost 库

c++ - 如何减少内存使用 - 可能的内存泄漏

c# - 将数组中的所有元素初始化为 NaN 的最快方法是什么?

c++ - 为什么大小为零字节的分配成功?

C++ - 为什么在没有明显的构造函数匹配时这段代码可以编译?