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

问题描述

有没有办法使用>

解决方案

要在堆栈上分配,可以通过值声明您的对象为局部变量使用alloca获取一个指针,然后使用in-place new操作符:

  void * p = alloca(sizeof(Whatever) ); 
new(p)Whatever(constructorArguments);但是,使用alloca和in-place new可以确保内存在返回时被释放,你可以使用alloca和in-place new。 up自动析构函数调用。如果你只是试图确保内存在退出范围后释放,请考虑使用 std :: auto_ptr< T> 或一些其他智能指针类型。 p>

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.

解决方案

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);

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.

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

06-12 13:57