6

Are there any compiler flags to enforce next rules?

The generation of the implicitly-defined copy constructor is deprecated if T has a user-defined destructor or user-defined copy assignment operator.

The generation of the implicitly-defined copy assignment operator is deprecated(since C++11) if T has a user-declared destructor or user-declared copy constructor.

I'm interested to enforce the rules in any of Clang, Visual Studio 2013 or GCC as the codebase will be compiled with all of them.

Mircea Ispas
  • 20,260
  • 32
  • 123
  • 211
  • You could just inherit from `noncopyable`:http://www.boost.org/doc/libs/1_55_0/libs/utility/utility.htm#Class_noncopyable – EdChum Oct 08 '14 at 09:37
  • For VS you could activate "warning-as-errors" – Marco A. Oct 08 '14 at 09:39
  • @MarcoA. Is it a warning? In which version and at what warning level? – Mircea Ispas Oct 08 '14 at 09:39
  • @EdChum I want to make the object copyable, but sometimes one might forget adding assignment operator/copy constructor – Mircea Ispas Oct 08 '14 at 09:40
  • I'm not sure it's a warning but it should be. If it is, you can surely turn that on – Marco A. Oct 08 '14 at 09:40
  • @Marco On their [Explicitly Defaulted and Deleted Functions](http://msdn.microsoft.com/en-us/library/dn457344.aspx) page they explicitly mention that they won't emit a warning. Not sure if you can still force the compiler to emit one, though. –  Oct 08 '14 at 10:00

1 Answers1

6

This bug report mentions this test case which doesn't emit a warning in gcc:

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

int main() {
 W w {};
 W v = w;
}

Refer to Johnathan Wakely's comment:

That's not true, the compiler can (and does) warn about legal code.

I'm confirming this, we will want the warning at some point, and it would allow us to improve this part of the -Weffc++ warnings:

* Item 11: Define a copy constructor and an assignment operator for classes with dynamically allocated memory.

(see PR 16166 for more details)

Maybe we could call this warning -Wdeprecated-special-members, and have it enabled -Weffc++ and in C++11 also by -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 emit a warning in this case:

Additionally, the C++11 standard specifies the following additional rules:

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

  • If a copy-assignment 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 emit a warning.