new 在堆栈而不是堆上(如 alloca 与 malloc)

2022-01-22 00:00:00 stack c++ new-operator

有没有办法使用 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.

相关文章