How delete a pointer of classes which has pointer members?

a 夏天 提交于 2019-12-06 07:59:41

问题


I mean, if i have some class like:

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

when i call delete pa, will pi be deleted?


回答1:


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;
};



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/9498384/how-delete-a-pointer-of-classes-which-has-pointer-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!