5

Is it possible to trigger compiler warning when a class breaks rule-of-three (or rule-of-five)?

This feature sounds easy to implement and is very useful in safety critical software but I can't find it anywhere in documentation or Google search results.

Melebius
  • 6,183
  • 4
  • 39
  • 52
JD.
  • 455
  • 6
  • 15
  • 2
    This might be idealist claptrap but IMHO it's far better to build your classes in such a way that you never need to implement the functions required for the rule-of-three or the rule-of-five. – Bathsheba Dec 07 '16 at 11:56
  • @Bathsheba absolutely agree. If you're not using rule of zero then your code is not sufficiently decomposed. – Richard Hodges Dec 07 '16 at 11:57
  • 1
    I personally would not like to have a check for Rule of five as I'm not sure it's a good guideline. Please check this discussion by Howard Hinnant: http://stackoverflow.com/a/38687106/1989995 – alexeykuzmin0 Dec 07 '16 at 12:06
  • Rule of zero is great but only works because people are following rule of five elsewhere. Someone has gotta implement the special member functions eventually. – Ryan Haining Apr 29 '19 at 16:30

3 Answers3

5

You can use the compiler flag -Weffc++ for GCC

Swapnil
  • 1,424
  • 2
  • 19
  • 30
3

clang-tidy can catch such mistakes. Given this file:

// badstyle.cpp
class Type {
  Type(const Type&) { }

  ~Type() { }
};

And this command:

$ clang-tidy badstyle.cpp -checks=cppcoreguidelines-*

My output is:

badstyle.cpp:2:7: warning: class 'Type' defines a non-default destructor and a 
copy constructor but does not define a copy assignment operator, a move constructor
or a move assignment operator [cppcoreguidelines-special-member-functions]
class Type {
  ^
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
2

Visual Studio 2017 RC states to have some "Checkers for enforcing the C++ Core Guidelines". Since the "Rule of five" is one of the most easily checked rules, I believe it's implemented.

alexeykuzmin0
  • 6,344
  • 2
  • 28
  • 51