cathgreen
cathgreen

Reputation: 21

In C++, can I skip defining assignment operator after defining my own copy constructor?

When I define a class, I need to define my own copy constructor if I need deep-copy. Then, is it necessary to define the assignment operator as well? If it is skipped, does the assignment do shallow copy?

Upvotes: 0

Views: 141

Answers (2)

Caleth
Caleth

Reputation: 62636

It is generally preferable to define data members such that you don't need to write a copy constructor (nor a copy assignment operator).

Instead of

class Foo {
    Bar * data = nullptr;
public:
    explicit Foo(const Bar & x) : data(new Bar(x)) {}
    ~Foo() { delete data; }
    Foo(const Foo & other) : data(new Bar(*other.data)) {}
    Foo& operator=(const Foo & other) { delete data; data = new Bar(*other.data); return *this; }
};

You have

class Foo {
    Bar data;
public:
    explicit Foo(const Bar & x) : data(x) {}
};

This is known as the Rule of Zero

Upvotes: 1

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36401

Yes you need. This is known as the Rule of Three: when one of copy-ctor, assignment-operator or dtor is defined, the two others must probably be defined. Exceptions exists but in standard cases, you must...

Since C++11, Rule of Five applies to tackle the move semantics.

Upvotes: 5

Related Questions