这里有人用过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/