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)


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01