6

I mean, if i have some class like:

class A{
    int* pi;
};
*A pa;

when i call delete pa, will pi be deleted?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
iloahz
  • 4,491
  • 8
  • 23
  • 31
  • It will be if you code it to be. It won't be if you code it not to be. Decide which you want and code that. – David Schwartz Feb 29 '12 at 11:43
  • Avoid this with standard library containers or smart pointers as members. – stefaanv Feb 29 '12 at 11:59
  • No. But note it will call the destructor where you can do clean up of the A instance. If you want to delete pi there then you can do that. **BUT** you must make sure you correctly own the pointer first. Loop up [rule of three](http://stackoverflow.com/questions/4172722). – Martin York Feb 29 '12 at 15:36

3 Answers3

12

You need to define a destructor to delete pi;. In addition you also need to define a copy constructor and assignment operator otherwise when an instance of A is copied two objects will be pointing to the same int, which will be deleted when one of the instances of A is destructed leaving the other instance of A with a dangling pointer.

For example:

class A
{
public:
    // Constructor.
    A(int a_value) : pi(new int(a_value)) {}

    // Destructor.
    ~A() { delete pi; }

    // Copy constructor.
    A(const A& a_in): pi(new int(*a_in.pi)) {}

    // Assignment operator.
    A& operator=(const A& a_in)
    {
        if (this != &a_in)
        {
            *pi = *a_in.pi;
        }
        return *this;
    }
private:
    int* pi;
};
hmjd
  • 120,187
  • 20
  • 207
  • 252
1

You should implement a destructor, ~A(), that takes care of cleaning up A's stuff. Afterwards, calling delete on a pointer of type A will clean-up everything.

foxx1337
  • 1,859
  • 3
  • 19
  • 23
  • 1
    But always remember that, if you need a destructor, you almost certainly need a copy constructor and copy-assignment operator too, per the [Rule of Three](http://stackoverflow.com/questions/4172722) – Mike Seymour Feb 29 '12 at 11:45
1

You will need to write a destructor to delete all pointer type members. Something like:

class A
{
    int *pi;
  public:
    ~A(){delete pi;}
};

You will need to ensure that your constructor assigns a value to pi( at least a NULL). and like the answer from @hmjd, you will need to implement or hide the copy constructor and assignment operators. Look for the rule of three here: http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29

go4sri
  • 1,490
  • 2
  • 15
  • 29