ggrr
ggrr

Reputation: 7867

Is it possible to override the destructor of MyClass* (not MyClass)?

for example, I have a class with different containers to hold MyClass object created by new operator:

class A{
    MyClass* m;
    vector<MyClass*> vm;
    vector<vector<MyClass> > vvm;
    pair<int,MyClass*> pim;
};

I want to delete all MyClass object in A when A is destroyed, is it possible to override the destructor of MyClass* like:

~MyClass*(){
    delete *this;
}

to replace custom destructor:

~A(){
    delete m;
    for(MyClass* m : this->vm){
        delete m;
    }
    for(vector<MyClass*> vm : this->vvm){
        for(MyClass* m : this->vm){
            delete m;
        }
    }
    delete pim.second;
}

so that I am no need to add new code when a type of container is added to hold the reference of MyClass?

Upvotes: 0

Views: 95

Answers (2)

Chickenchaser
Chickenchaser

Reputation: 184

An instance of MyClass is created in outside, and you wants that the instance of MyClass is deleted when instance of A is deleted?

If lifecycle of instance of MyClass is dependent to A, then just

class A {
private:
MyClass m;
}

or If not, then delete instance of MyClass outside.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206717

If you have the liberty of using std::shared_ptr<MyClass> instead of raw pointers, you can simplify the destructor of A.

class A {

   public:
      ~A() {} // That's all you need. You can even omit it.

   private:
      std::shared_ptr<MyClass> m;
      vector<std::shared_ptr<MyClass>> vm;
      vector<vector<MyClass> > vvm;
      pair<int,std::shared_ptr<MyClass>> pim;

};

Upvotes: 2

Related Questions