Objects created inside a method

I was wondering where objects instantiated inside a local method stored? As far as my knowledge goes, objects are stored in the heap, and their references are stored in the stack. If so, then when the function returns,and the reference to the object no longer exists (since the local stack frame of the function is popped), does the object stay in the heap, or do we have to delete it manually (or using garbage collection, as in Java)?


It depends what you plan to do with that object, if you return the object then it's lifetime is extended. If you create it as a temporary then there are two possible outcomes.

  • If you Create the object with new . If you create a pointer to a new object then the pointer will be deleted when the method goes out of scope. But the object remains causing memory leaks, the object will need to be explicitly deleted.

  • If you do not use new . The object will be deleted when the scope ends.

  • Both of these outcomes assume you do not return the object and you instantiated it as temporary object in the function.

    Here is some sample code:

    class ObjectClass {
    public:
            ObjectClass() {}
    
    };
    
    void myFunction() {
            ObjectClass my_obj(); //memory is handled for you
            ObjectClass * my_dynamic_obj = new ObjectClass();
            delete my_dynamic_obj; //if delete is not called then
            // the pointer my_dynamic_obj will be deleted but the object itself will remain
            return;
    }
    
    main() {
            myFunction();
            return 0;
    }
    
    链接地址: http://www.djcxy.com/p/79798.html

    上一篇: Windows堆管理器和堆段

    下一篇: 在方法内创建的对象