c++ - Delete dynamically allocated derived objects - Polymorphism -


i cannot figure out how delete dynamically allocated subclasses through basepointer. allocation in app-class , how delete allocated objects withing main-method?

#include <iostream>  using namespace std;  class base {  public:    virtual void print() = 0;    virtual ~base() {       cout << "base destructor\n";    } };  class sub1 : public base {  public:    void print() {       cout << "i sub1!\n";    }    ~sub1() {        cout << "sub1 destructor\n";    } };  class sub2 : public base {  public:    void print() {       cout << "i sub2!\n";    }    ~sub2() {        cout << "sub2 destructor\n";    } };  class app {  public:     app(base *&b) {       b = new sub1;       b = new sub2;    } };   int main() {     base *b;    b = null;     app app(b);    return 0;  } 

the minimum fix leaks be:

class app {  public:     app(base *&b) {       b = new sub1;       delete b;      // chance since next statement overwrites pointer.       b = new sub2;    } };   int main() {     base *b;    b = null;     app app(b);     delete b;     return 0; } 

but doesn't seem sensible program. need figure out you're trying sub1 , sub2. can't have single pointer pointing 2 separate objects @ same time.

furthermore, better off learning use std::unique_ptr, since keeps ownership of points , deletes when appropriate.

so using std::unique_ptr minimum change code is:

class app {  public:     app(std::unique_ptr<base> & b) {       b.reset(new sub1);       b.reset(new sub2);    } };   int main() {     std::unique_ptr<base> b;     app app(b);     return 0; } 

there no manual delete statements. , there no memory leaks.

(the useless sub1 issue still there, that's design issue have figure out since don't know want program in end.)


Comments

Popular posts from this blog

asp.net mvc - Cannot display error message on Editor or EditorFor -

Reliable way to get Windows Version from registry -

python - No exponential form of the z-axis in matplotlib-3D-plots -