new on stack instead of heap (like alloca vs malloc)(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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:new 在堆栈而不是堆上(如 alloca 与 malloc)
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
