什么是C ++中的就地构造函数? [英] What is an in-place constructor in C++?

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

问题描述


可能重复:

C ++的位置新建

C ++?

Datatype * x = new(y)Datatype();

e.g. Datatype *x = new(y) Datatype();

推荐答案

它允许你提供数据将被分配的内存,而不用 new 操作符分配它。例如:

This is called the placement new operator. It allows you to supply the memory the data will be allocated in without having the new operator allocate it. For example:

Foo * f = new Foo();

以上将为您分配内存。

void * fm = malloc(sizeof(Foo));
Foo *f = new (fm) Foo(); 

上面将使用调用 malloc new 将不再分配。然而,你不限于类。您可以使用刊登位置新的运算子来分配调用 new 的任何类型。

The above will use the memory allocated by the call to malloc. new will not allocate any more. You are not, however, limited to classes. You can use a placement new operator for any type you would allocate with a call to new.

'for placement new是您不应通过使用 delete 关键字释放对展示位置新操作符的调用分配的内存。您将通过直接调用析构函数来销毁对象。

A 'gotcha' for placement new is that you should not release the memory allocated by a call to the placement new operator using the delete keyword. You will destroy the object by calling the destructor directly.

f->~Foo();

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

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