Septagram
Septagram

Reputation: 9785

C++: Is default copy constructor affected by presence of other constructors and destructor?

As we know, if any constructor is declared (copy constructor included), default constructor (the one that takes no arguments) is not implicitly created. Does the same happen with a default copy constructor (the one that performs shallow copy of an object)? Also, does the presence of destructor affect this anyhow?

Upvotes: 8

Views: 1803

Answers (5)

Howard Hinnant
Howard Hinnant

Reputation: 218700

The answers here are correct but not complete. They are correct for C++98 and C++03. In C++11 you will not get a copy constructor if you have declared a move constructor or move assignment operator. Furthermore if you have declared a copy assignment operator or a destructor, the implicit generation of the copy constructor is deprecated. 12.8 [class.copy]:

If the class definition does not explicitly declare a copy constructor, there is no user-declared move constructor, and there is no user-declared move assignment operator, a copy constructor is implicitly declared as defaulted (8.4.2). Such an implicit declaration is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.

Upvotes: 6

dubnde
dubnde

Reputation: 4431

12.8 #4 Copying class objects

If the class definition does not explicitly declare a copy constructor, one is declared implicitly

And the destructor plays no part

Upvotes: 9

Alexandre C.
Alexandre C.

Reputation: 56956

No. And note that

MyClass
{
    template <typename T> MyClass(const T&);
};

does not provide a copy constructor, and a default one is generated.

Upvotes: 3

Mario
Mario

Reputation: 36487

The default copy constructor is always created, unless you define your own one. The constructor with no arguments isn't defined with any other constructor present to avoid calling it and therefore skipping the real constructor(s)'s code.

Upvotes: 1

Gareth McCaughan
Gareth McCaughan

Reputation: 19971

No. You'll get a default copy constructor unless you supply your own copy constructor, and the presence or absence of a destructor makes no difference.

Upvotes: 3

Related Questions