Arumand
Arumand

Reputation: 1894

How to delete instance class inside class

Consider this code snippet:

#include <iostream>

using namespace std;

class X {
  public:
    class Z {
      public:
        void f() {
          cout << "Z().f()" << endl;
        }
    };

    class Y {
      public:
        int A;
        Y(int x) {
          A = x;
        }

        int c() {
          return A;
        }
    };

    public:
      Z* z;

      // How to free Y instance ?
      Y* a(int x) {
        Y* y = new Y(x);
        return y;
      }

    public:
      X() {
        z = new Z();
      }

      ~X() {
        delete z;
      }
};

int main(void) {
  int a;
  X* x = new X();
  cout << "input :" << endl;
  cin >> a;
  cout << "result : " << x->a(a)->c() << endl;
  x->z->f();
  delete x;
  return 0;
}

While Z object can easily be freed on ~X(), i am curious how to free Y one ? Since i am not assigning any variable to hold its memory address.

Btw, what's the terminology for something like this ? x->a(a)->c()

Thank you. :)

Upvotes: 0

Views: 253

Answers (2)

juanchopanza
juanchopanza

Reputation: 227390

// How to free Y instance ?
Y* a(int x) {
  Y* y = new Y(x);
  return y;
}

Well, the problem is that it is not clear from the function prototype who is responsible for deleting the instance. But since only the caller has a handle to the instance, then it should be the called's responsibility to delete. This should be well documented. But the best approach would be to use a smart pointer with the right ownership semantics. In this case, std::unique_ptr<Y> seems like an appropriate match, and the mere fact of using it makes the intent clear, removing the need for documentation concerning ownership:

std::unique_ptr<Y> a(int x)
{
  return std::unique_ptr<Y>( new Y(x) );
}

Upvotes: 4

David G
David G

Reputation: 96800

You're returning the memory from the function, so it is up to the caller to delete it:

X x;

Y *ptr = x.a(5);

delete ptr;

Hopefully you never have to do something like this. If you must then it's recommended that you use smart pointers like a shared_ptr or unique_ptr.

std::unique_ptr<Y> a(int x) {
  return std::unique_ptr<Y>(new Y(x));
}

With this, you never have to worry about deleting the instance as the destructor of the pointer class holds that responsibility.

Upvotes: 1

Related Questions