How to Convert beween Stack and Heap Objects

前端 未结 7 912
暖寄归人
暖寄归人 2021-01-05 23:16

Example:

Class *_obj1;
Class *_obj2;

void doThis(Class *obj) {}

void create() {
    Class *obj1 = new Class();
    Class obj2;

    doThis(obj1);
    doThi         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 23:22

    Taking the address of a stack variable won't magically transfer it into heap. You need to write a proper copy-constructor for your class and use _obj2 = new Class(obj2);.

    As for STL containers, they allocate their data on the heap anyway, why would you want to allocate container itself on the heap? Put them in a scope that will keep them alive as long as you need them.

提交回复
热议问题