“placement new"有什么用? [英] What uses are there for "placement new"?

查看:39
本文介绍了“placement new"有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Has anyone here ever used C++'s "placement new"? If so, what for? It looks to me like it would only be useful on memory-mapped hardware.

推荐答案

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

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

Placement new allows you to construct an object in memory that's already allocated.

You may want to do this for optimization when you need to construct multiple instances of an object, and it is faster not to re-allocate memory each time you need a new instance. Instead, it might be more efficient to perform a single allocation for a chunk of memory that can hold multiple objects, even though you don't want to use all of it at once.

DevX 给出了一个很好的例子:

DevX gives a good example:

标准 C++ 也支持放置new 运算符,它构造一个预分配缓冲区上的对象.这个在构建内存池时很有用,垃圾收集器或只是当性能和异常安全是最重要的(没有危险自内存分配失败已经分配,​​并且在一个对象上构造一个对象预先分配的缓冲区花费的时间更少):

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

您可能还想确保在关键代码的某个部分(例如,在由起搏器执行的代码中)没有分配失败.在这种情况下,您可能希望更早地分配内存,然后在临界区中使用新的布局.

You may also want to be sure there can be no allocation failure at a certain part of critical code (for instance, in code executed by a pacemaker). In that case you would want to allocate memory earlier, then use placement new within the critical section.

您不应该释放每个使用内存缓冲区的对象.相反,您应该只删除 [] 原始缓冲区.然后您必须手动调用类的析构函数.有关这方面的好建议,请参阅 Stroustrup 的常见问题解答:是否有放置删除"??

You should not deallocate every object that is using the memory buffer. Instead you should delete[] only the original buffer. You would have to then call the destructors of your classes manually. For a good suggestion on this, please see Stroustrup's FAQ on: Is there a "placement delete"?

这篇关于“placement new"有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆