new on stack instead of heap (like alloca vs malloc)

后端 未结 4 1903
滥情空心
滥情空心 2021-02-01 22:50

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 o

4条回答
  •  旧时难觅i
    2021-02-01 23:03

    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 or some other smart pointer type.

提交回复
热议问题