如何在已分配的内存上调用构造函数? [英] How to call a constructor on an already allocated memory?

查看:145
本文介绍了如何在已分配的内存上调用构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在已经分配的内存区域上调用构造函数?

How can I call a constructor on a memory region that is already allocated?

推荐答案

您可以使用放置新的构造函数

You can use the placement new constructor, which takes an address.

Foo* foo = new (your_memory_address_here) Foo ();

C ++常见问题精简版 MSDN 。您唯一需要确保内存正确对齐的内容( malloc 应该返回适​​合任何内容的内存,但是要提防可能需要使用SSE之类的东西对齐到16个字节左右的边界)。

Take a look at a more detailed explanation at the C++ FAQ lite or the MSDN. The only thing you need to make sure that the memory is properly aligned (malloc is supposed to return memory that is properly aligned for anything, but beware of things like SSE which may need alignment to 16 bytes boundaries or so).

这篇关于如何在已分配的内存上调用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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