copy constructor of a class which has self-pointer to itself in C++?

大兔子大兔子 提交于 2020-01-01 19:34:07

问题


I wanted to ask that how will we implement a copy constructor of a class which has self pointer to itself as its data member, i want to implement a deep copy,

class City
{
    string name;
    City* parent;
public:
    City(string nam, double dcov);
    City(string nam, double dcov, City* c);
City(const City& obj)

{

    this-> name = obj.name;
// how to assign parent 
parent = new City(??)
}
    ~City();

    void setName(string name1);
    void setDistanceCovered(int dist);
    string getName();
    double getDistanceCovered();
    City* getParent(){return parent;}


};

I am confused that this line // how to assign parent parent = new City(??)will call constructor again instead of deep copy? Regards.


回答1:


How about

if (obj.parent != NULL)
    parent = new City(*obj.parent)
else
    parent = NULL;

This should work unless you have cycles in the parent hierarchy.




回答2:


The answer of Kristian is perfectly good.

In the case where you do not terminate the chain with a NULL pointer but a reference to self (is it that you are trying to say with "self pointer to itself"?), you can do this:

if(obj.parent == NULL)
    parent = NULL;
else if(obj.parent==&obj)
    parent=this;
else parent = new City(*obj.parent);

In the case you have cycles that you want to avoid, you need to use a temporary registering map:

class City
{
    string name;
    City* parent;

    /// The DB to avoid for infinite loops in case of circular references
    static
    std::map<const City*,City*>& parents_db()
    {   static std::map<const City*,City*> ret;
        return ret;
    }

    /// The cloning function that make use of the DB
    static
    City* clone_parent(const City *_parent)
    {   if(_parent)
        {   City *& cloned_parent = parents_db()[_parent];
            if(!cloned_parent)
               cloned_parent = new City(_parent);
            return cloned_parent;
        }
        return NULL;
    }

    /// The private constructor that make use of the cloning function
    City(const City* obj) :
        name(obj->name),
        parent(clone_parent(obj->parent))
    {}

public:
    City(string nam, double dcov);
    City(string nam, double dcov, City* c);

    /// The public constructor that cleans up the DB after cloning the hierarchy
    City(const City& obj) :
        name(obj.name),
        parent(clone_parent(obj.parent))
    {   parents_db().clear();
    }

    ~City();

    void setName(string name1);
    void setDistanceCovered(int dist);
    string getName();
    double getDistanceCovered();
    City* getParent(){return parent;}


};


来源:https://stackoverflow.com/questions/21628532/copy-constructor-of-a-class-which-has-self-pointer-to-itself-in-c

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