smallB
smallB

Reputation: 17110

Copy constructor

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?

Upvotes: 0

Views: 179

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

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

Upvotes: 2

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506847

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
        /* ... */
    }

Upvotes: 4

Related Questions