0

This answer explains that what happens when we create/remove object with and without new/delete. Now consider three object top, mid and bottom. top is created WITHOUT new, and it goes out of scope only when whole program ends. Now within top there is and infinite while loop which keep creating and deleting mid objects by using new and delete. And on creation mid objects create some bottom objects within them, WITHOUT new, which are never deleted explicitly.

My question is, will bottom objects be automatically deleted on delete call on mid? It seems scope of bottom is in whole top. So every created bottom object will never go out of scope. Right?

Sample Code:

Main:
    Top();

Top.h:
    class Top{
        public:        
            vector<Mid> midVec;
    }

Top::Top(){
    canExit = false;
    run();
}
Top::run(){
    while(!canExit){
        //dosomething
        midVec.push_back(new Mid(););
        //againdosomemorething - they use Mid and things within it.

        vector<Mid>::iterator b, e;
        //iterate over midVec check for some condition and identify some to delete.
        // call ***delete*** on identified objects.

    }
}


Mid::Mid(){
    for(int i =0; i<someCount; i++){
        Bottom obj = Bottom();
        umB.insert(std::make_pair<int, Bottom>(i, obj));
        umBPTR.insert(std::make_pair<int, Bottom*>(i, &obj));
    } 

}

Mid.h
    class Mid{
    public:
        unordered_map<int, Bottom> umB;
        unordered_map<int, Bottom*> umBPTR;
    }
Community
  • 1
  • 1
PHcoDer
  • 996
  • 7
  • 19
  • 1
    The answer would depend on details you haven't told us. It would be best if you presented a complete, fully compilable and runnable test program and asked whether it has a memory leak or not. – zwol Nov 25 '16 at 16:30
  • 1. Agree with zwol, give Your code. 2. In very short: probably You need (good designed) DESTRUCTOR – Jacek Cz Nov 25 '16 at 16:32
  • @zwol Done added sample code. – PHcoDer Nov 25 '16 at 16:46
  • @JacekCz Done added sample code. – PHcoDer Nov 25 '16 at 16:46
  • 1
    better to provide [mcve](http://stackoverflow.com/help/mcve) code, and you may need to learn more about scope in c++. – apple apple Nov 25 '16 at 16:49
  • This code is unusable, cant compile etc. BTW visible fragments are without understanding basic ideas of OOP and C++ (variables in construtor) – Jacek Cz Nov 25 '16 at 16:52
  • your "bottom" objects in the unordered map will be deleted after the constructor finishes. Their scope is the body of the `Mid` constructor. – Noidea Nov 25 '16 at 16:54
  • @Noidea corrected. They are actually declared in H files. – PHcoDer Nov 25 '16 at 17:01

0 Answers0