How to disable implicitly defined copy constructor creation when there is a user-defined destructor

Are there any compiler flags for applying the following rules?

Generation of an implicit copy constructor is deprecated if T has a user-defined destructor or user-defined copy assignment operator.

Generation of an implicit copy assignment operator is deprecated (since C ++ 11) if T has a user-declared destructor or a user-declared copy constructor.

I am interested in following the rules in any of Clang, Visual Studio 2013 or GCC, since the code base will be compiled with all of them.

+5
source share
1 answer

This report points to this test case that does not generate a warning in gcc:

struct W { int a; ~W() { a = 9; } }; int main() { W w {}; W v = w; } 

Refer to Jonathan Wackel's comment:

This is not so, the compiler can (and does) warn about legal code.

I confirm this, at some point we will need a warning, and this will allow us to improve this part of the warnings -Weffc++ :

* Clause 11: Define the copy constructor and assignment operator for classes with dynamically allocated memory.

(see PR 16166 for more details)

Perhaps we could trigger this warning -Wdeprecated-special-members and enable -Weffc++ , and in C ++ 11 also -Wdeprecated

Clang already warns about this with -Wdeprecated :

 main.cpp:3:3: warning: definition of implicit copy constructor for 'W' is deprecated because it has a user-declared destructor [-Wdeprecated] ~W() { a = 9; } ^ main.cpp:8:8: note: implicit copy constructor for 'W' first required here W v = w; 

Microsoft explicitly states that Visual Studio will not issue a warning in this case:

In addition, the following additional rules are specified in the C ++ 11 standard:

  • If the constructor or destructor is explicitly declared, then the automatic generation of the copy assignment operator is deprecated.

  • If the copy operator or destructor is explicitly declared, then automatic generation of the copy constructor is deprecated.

In both cases, Visual Studio continues to automatically generate the necessary functions implicitly and does not generate a warning.

+5
source

Source: https://habr.com/ru/post/1204240/


All Articles