How to Convert beween Stack and Heap Objects

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

    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?

    This line:

    _obj2 = &obj2;
    

    Change to:

    _obj2 = new Class(obj2);  // Create an object on the heap invoking the copy constructor.
    

    I want a straight answer, not an arrogant "you're doing it wrong" as so many have done.

    Thats as straight an answer as you can get. Obviously you are new to C++, So I am sure this will nto work as intended because you have probably made a couple of mistakes in the defintion of the class "Class" (by the way terrible name).

    Also, converting back to a stack object would be useful as well.

    class obj3(*_obj2);  // dereference the heap object pass it to the copy constructor.
    

    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?

    Why do you dynamically allocate the vector. Just create it locally.

    std::vector funct()
    {
        std::vector   vecString;
        // fill your vector here.
    
        return vecString;  // Notice no dynamic allocation with new,
    }
    

    Using new/delete is using C++ like C. What you need to read up on is smart pointers. These are obejcts that control the lifespan of the object and automatically delete the object when they go out of scope.

    std::auto_ptr   x(new Class);
    

    Here x is a smart pointer (of type auto_ptr) when it goes out of scope the object will be deleted. But you can return an auto_ptr to the calling function and it will be safely transfered out of the function. Its actually a lot more complicated than that and you need a book.

    Obviously if you create them as stack objects it fails because they're immediately deallocated,

    Its de'allocated when it goes out of scope.

    but I've been told (again, by a very high-ranking member) that dynamically allocating them can corrupt the heap.

    If you do it incorrectly. Which given your knowledge is very likely. But hard to verify since you have not provided the definition of Class.

    So what's the right way to do it?

    1. Learn why you should use stack objects
    2. Learn what smart pointers are.
    3. Learn how to use smart pointers to control lifespans of objects.
    4. Learn the different types of smart pointers.
    5. Look up what the separation of concerns is (you are not following this basic principle).

提交回复
热议问题