什么是C ++构造“placement new”的用途? [英] What are uses of the C++ construct "placement new"?

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

问题描述

我刚刚学习了一个名为placement new的C ++结构。它允许您精确控制指针指向内存中的位置。它看起来像这样:

I just learned about the C++ construct called "placement new". It allows you to exactly control where a pointer points to in memory. It looks like this:

 #include <new>        // Must #include this to use "placement new"
 #include "Fred.h"     // Declaration of class Fred

 void someCode()
 {
   char memory[sizeof(Fred)];
   void* place = memory;

   Fred* f = new(place) Fred();   // Create a pointer to a Fred(),
                                  // stored at "place"

   // The pointers f and place will be equal

   ...
 }

(例如 C ++ FAQ Lite


在此示例中, this 指针将等于 place


我已经看到它在我们团队的代码中使用了一两次。根据你的经验,这个结构能够实现什么?其他指针语言有类似的结构吗?对我来说,似乎让人联想到FORTRAN中的等价,它允许不同的变量占据内存中的相同位置。

I've seen it used in our team's code once or twice. In your experience, what does this construct enable? Do other pointer languages have similar constructs? To me, it seems reminiscent of equivalence in FORTRAN, which allows disparate variables to occupy the same location in memory.

推荐答案

它允许你做自己的内存管理。通常这会让你在最好的稍微提高的性能,但有时是一个大的胜利。例如,如果你的程序使用了大量的标准大小的对象,你可能希望创建一个具有一个大内存分配的池。

It allows you to do your own memory management. Usually this will get you at best marginally improved performance, but sometimes it's a big win. For example, if your program is using a large number of standard-sized objects, you might well want to make a pool with one large memory allocation.

这种东西也在C中完成,但由于C中没有构造函数,因此不需要任何语言支持。

This sort of thing was also done in C, but since there are no constructors in C it didn't require any language support.

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

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