How delete a pointer of classes which has pointer members?
Asked Answered
M

3

6

I mean, if i have some class like:

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

when i call delete pa, will pi be deleted?

Mariehamn answered 29/2, 2012 at 11:35 Comment(3)
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.Lucio
Avoid this with standard library containers or smart pointers as members.Bleachers
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.Hillary
M
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;
};
Mckenney answered 29/2, 2012 at 11:39 Comment(0)
P
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.

Preadamite answered 29/2, 2012 at 11:37 Comment(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 ThreeVilleneuve
G
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

Griner answered 29/2, 2012 at 11:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.