C++ 构造“placement new"的用途是什么?

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

问题描述

限时送ChatGPT账号..

我刚刚了解了名为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精简版)

在这个例子中,Fred 的 this 指针将等于 place.

(example from C++ FAQ Lite)

In this example, the this pointer of Fred will be equal to place.

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

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"的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:内存管理、堆损坏和 C++ 下一篇:如何编写密码安全的类?

相关文章