复制一个在C ++中具有自我指针的类的构造函数?

时间:2014-02-07 13:03:24

标签: c++ c++11 deep-copy self-reference this-pointer

我想问一下,我们将如何实现一个类的复制构造函数,该类具有自身指针作为其数据成员,我想实现深层复制,

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


};

我很困惑这行// how to assign parent parent = new City(??)会再次调用构造函数而不是深层复制吗? 问候。

2 个答案:

答案 0 :(得分:7)

怎么样

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

除非您在父层次结构中有循环,否则这应该有效。

答案 1 :(得分:0)

克里斯蒂安的答案非常好。

如果您没有使用NULL指针终止链,而是使用对self的引用(您试图用&#34说明;自我指针指向自身"?),您可以这样做:

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

如果您想要避免循环,则需要使用临时注册地图:

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


};