动态分配堆栈上的内存 [英] Dynamically allocating memory on stack

查看:135
本文介绍了动态分配堆栈上的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这样的代码:

#include <iostream>

int main()
{
    int a;
    int* p = new (&a) int(2);
    std::cout << a << std::endl;
    // delete p; error BLOCK TYPE IS INVALID
    std::cin.get();
    return 0;
}

输出为:

2

为什么可以动态分配内存在堆栈? (我认为堆是正确的地方做这个)。

Why is it possible to dynamically allocate memory on stack? (I thought that heap is the right place to do this). And, why does delete operator return error in this case, but new operator work?

推荐答案

int* p = new (&a) int(2);

这称为placement-new。它不分配内存。它在 a 的同一内存中构造对象。在placement new中,是指定 new 运算符构造对象的内存区域的用户。在上面的代码中,通过在 new 关键字后面写入(& a)表达式来指定内存区域。由于& a 不是动态分配的内存,您不能 delete it:

This is called placement-new. It doesn't allocate memory. It constructs the object in the same memory of a. In placement new, it's the user who specifies the memory region where new operator constructs the object. In your code above, you specify the memory region by writing (&a) expression just after the new keyword. Since &a is not a dynamically allocated memory, you cannot delete it:

delete p; //runtime-error

这将给运行时错误,它试图删除内存中的变量 a

It would give runtime error, it attempts to delete the memory where the variable a resides.

但是,如果你动态分配内存,你可以删除它。让我们假设, A 是一些类,那么你应该这样做:

However, if you dynamically allocate the memory, then you can do delete it. Lets suppose, A is some class, then you should be doing this:

char *buffer = new char[sizeof(A)]; //allocate memory of sizeof(A);

///ASSUMPTION: the buffer is properly align as required by the type A
//use placement-new to construct an object at the specified memory region
A *pA = new (buffer) A(/*..parameters..*/); 

//...

//incorrect way to delete the memory!
//delete pA; //incorrect

//before deleting the memory you should be calling the destructor explicitly as
pA->~A(); //call the destructor explicitly - must do it

//now deallocate the memory as
delete []buffer;

这是placement-new的一个最简单的例子,只解释了语法。但是故事不会在这里结束;它是开始,并使其正常工作, buffer 指向的内存必须正确对齐对象类型,在上面的示例中,我简单地假设。在真正的代码中,你不能做这样危险的假设。现在阅读此常见问题:

This is simplest example of placement-new which explains the syntax only. But the story doesn't end here; it is the beginning and to make it work properly, the memory pointed to by buffer has to be aligned properly for the object type, and in the above example, I simply assumed so. In the real code, you cannot make such dangerous assumption. Now read this FAQ:

  • What is "placement new" and why would I use it?

这篇关于动态分配堆栈上的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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