开发者

Copy constructor

开发者 https://www.devze.com 2023-03-20 13:02 出处:网络
In class of this design: class X { X* left_; X* right_; X(const X&) }; when trying to implement cpy ctor I\'m getting into loop:

In class of this design:

class X
{
    X* left_;
    X* right_;
    X(const X&)
};

when trying to implement cpy ctor I'm getting into loop:

X::X(const X& pattern)
{
    if (this != &pattern)
    {
        left_ = new X(*pattern.left_);//this is the line
    }
}

As a solution to 开发者_运维知识库that I'm thinking of using memcpy + operator new() fnc, but is there better way to do it?


You have an infinitely large tree, as it looks like both your left_ and right_ pointers always point to another X? What else do you expect from copying such a large tree than always descending into another subtree?

You want to have a stop condition, like

    X::X(const X& pattern)
    :left_(0), right_(0)
    {
        if(pattern.left_)
            left_ = new X(*pattern.left_);//this is the line
        /* ... */
    }


If I understand you correctly from your comments on Johannes' answer, you only want to copy one generation of children? Make another constructor, e.g.

class X
{
public:
    X(const X& other)
        :left_(0), right_(0)
    {
        left_ = new X(*other.left_, 1);
    }

    X(const X& other, unsigned howDeep)
        :left_(0), right_(0)
    {
        if(howDeep == 0)
            return;
        left_ = new X(*other.left_, howDeep - 1);
    }
private:
    X* left_;
    X* right_;    
};
0

精彩评论

暂无评论...
验证码 换一张
取 消