Valentin Grigorev
Valentin Grigorev

Reputation: 145

Implicitly-generated constructors with explicit declaration of destructor

The thing is, 4th edition of C++ Programming language says:

In this particular case, if you forgot to delete a copy or move operation, no harm is done. A move operation is not implicitly generated for a class where the user has explicitly declared a destructor. Furthermore, the generation of copy operations is deprecated in this case (§44.2.3). This can be a good reason to explicitly define a destructor even where the compiler would have implicitly provided one (§17.2.3).

I've tried this code:

#include <iostream>
class Foo {
public:
    ~Foo() {}
}
int main() {
    Foo x;
    Foo y(x);
    return 0;
}

and there is no errors and exeptions here. I know that copy constructor should be generated implicitly in c++98, but 4th says that copy is deprecated. What does it mean?

Upvotes: 3

Views: 665

Answers (2)

nilo
nilo

Reputation: 1130

I know that copy constructor should be generated implicitly in c++98, but 4th says that copy is deprecated. What does it mean?

It means, as your test shows, that the copy constructor still will be generated, but that this may not be the case in future versions of the standard.

See C.21 for a best practice recommendation and corresponding clang-tidy check:

C.21: If you define or =delete any copy, move, or destructor function, define or =delete them all

Upvotes: 0

Nelfeal
Nelfeal

Reputation: 13269

My understanding is that an implicitly-declared constructor is not necessary implicitly-defined.

From cppreference :

Implicitly-declared copy constructor
If no user-defined copy constructors are provided for a class type (struct, class, or union), the compiler will always declare a copy constructor as a non-explicit inline public member of its class.

Implicitly-defined copy constructor
If the implicitly-declared copy constructor is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used.
The generation of the implicitly-defined copy constructor is deprecated if T has a user-defined destructor or user-defined copy assignment operator.

So in your case, the copy constructor is implicitly-declared but not implicitly-defined if not odr-used, which basically means it is not defined unless required somewhere.

See also : What is the distinction between implicitly-declared and implicitly-defined copy constructors?

Upvotes: 1

Related Questions