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

后端 未结 4 1904
滥情空心
滥情空心 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条回答
  •  说谎
    说谎 (楼主)
    2021-02-01 22:52

    Jeffrey Hantin is quite correct that you can use placement new to create it on the stack with alloca. But, seriously, why?! Instead, just do:

    class C { /* ... */ };
    
    void func() {
        C var;
        C *ptr = &var;
    
        // do whatever with ptr
    }
    

    You now have a pointer to an object allocated on the stack. And, it'll properly be destroyed when your function exists.

提交回复
热议问题