Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How delete a pointer of classes which has pointer members?

I mean, if i have some class like:

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

when i call delete pa, will pi be deleted?

like image 201
iloahz Avatar asked Dec 10 '22 02:12

iloahz


1 Answers

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;
};
like image 55
hmjd Avatar answered Mar 16 '23 13:03

hmjd