new 在堆栈而不是堆上(如 alloca 与 malloc) [英] new on stack instead of heap (like alloca vs malloc)

查看:35
本文介绍了new 在堆栈而不是堆上(如 alloca 与 malloc)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用 new 关键字在堆栈上分配(ala alloca)而不是堆上(malloc)?

Is there a way to use the new keyword to allocate on the stack (ala alloca) instead of heap (malloc) ?

我知道我可以自己破解,但我不想这样做.

I know I could hack up my own but I'd rather not.

推荐答案

要在栈上分配,要么将你的对象声明为局部变量按值,或者你可以实际使用alloca来获取一个指针,然后使用就地 new 运算符:

To allocate on the stack, either declare your object as a local variable by value, or you can actually use alloca to obtain a pointer and then use the in-place new operator:

void *p = alloca(sizeof(Whatever));
new (p) Whatever(constructorArguments);

但是,虽然使用 alloca 和 in-place new 可确保在返回时释放内存,但您放弃了自动析构函数调用.如果您只是想确保在退出范围时释放内存,请考虑使用 std::auto_ptr<T> 或其他一些智能指针类型.

However, while using alloca and in-place new ensures that the memory is freed on return, you give up automatic destructor calling. If you're just trying to ensure that the memory is freed upon exit from the scope, consider using std::auto_ptr<T> or some other smart pointer type.

这篇关于new 在堆栈而不是堆上(如 alloca 与 malloc)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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