How to Convert beween Stack and Heap Objects

前端 未结 7 795
暖寄归人
暖寄归人 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:33

    So, the first question is: if how can I convert the stack object (obj2) to a heap object so it's not deallocated after create() exits? I want a straight answer,

    The straight answer is: You can't "convert" an object between the stack and heap. You can create a copy of the object that lives in the other space, as others have pointed out, but that's it.

    The second question: the specific example of heap objects being "wrong" was creating a new vector* using the new operator. If dynamically allocating STL objects is wrong, then what's the right way? Obviously if you create them as stack objects it fails because they're immediately deallocated, but I've been told (again, by a very high-ranking member) that dynamically allocating them can corrupt the heap.

    Dynamically allocating STL objects will not on its own corrupt the heap. (No idea where you might have heard that.)

    If you want to use a stack-allocated STL object outside of the function that you created it in, you can't, since the stack space in which the object resides is only valid inside the function that created it.

    You can, however, return a copy of the object:

    std::vector SomeFunc()
    {
        std::vector myvector;
        // myvector.operations ...
        return myvector;
    }
    

    As I said, though, this will return a copy of the object, not the original object itself -- that would be impossible, since the stack that contains the object is unwound after the function returns.

    One other option is to have the caller pass in a reference / pointer to the object that your function manipulates, if this makes sense for your particular scenario:

    void SomeFunc(std::vector& destination)
    {
        // destination.operations ...
    }
    
    void AnotherFunc()
    {
        std::vector myvector;
        SomeFunc(myvector);
    }
    

    As you can see, you've still allocated everything on the stack, and you avoid the (sometimes consequential) overhead of relying on the copy-constructor to return a copy of the object.

提交回复
热议问题