In C ++, what do you do almost all the time?

There are a few things that I almost always do when I put a class in C ++.

1) Virtual destructor 2) Copy the constructor and assignment operator (I either implement them using the private Copy () function or declare them private, and therefore explicitly forbids the compiler to automatically generate them).

What things do you find almost always useful?

+5
source share
10 answers

I think the inclusion of gcc-flags -Wall, -Werrorand (it's fun) -Weffc++helps to capture a lot of potential problems. On the gcc man page:

  -Weffc++ (C++ only)
      Warn about violations of the following style guidelines from Scott
      Meyers’ Effective C++ book:

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

      ·   Item 12:  Prefer initialization to assignment in constructors.

      ·   Item 14:  Make destructors virtual in base classes.

      ·   Item 15:  Have "operator=" return a reference to *this.

      ·   Item 23:  Don’t try to return a reference when you must return
          an object.

      and about violations of the following style guidelines from Scott
      Meyers’ More Effective C++ book:

      ·   Item 6:  Distinguish between prefix and postfix forms of incre-
          ment and decrement operators.

      ·   Item 7:  Never overload "&&", "││", or ",".

      If you use this option, you should be aware that the standard
      library headers do not obey all of these guidelines; you can use
      grep -v to filter out those warnings.
+10
source

Oddly enough, most of the suggestions here are what I do not specifically do.

  • dtors , . , , dtors ( ).
  • copy ctor/ op, , , . , . ctor, , .
  • . , , . ToString().
  • oper < <, . (ostream). < , . , < , Display(), .
+14

, , , doxygen , .

- , , . , . , .

+4

. , , gcc - " ", ...

+3

+3

,

operator string () const;

friend ostream& operator << (ostream&, const MyClass&);
+2

#ifndef __SOMEDEFINE__
#define __SOMEDEFINE__

#endif

VS

#pragma warning(disable: 4786)

,

#include <inttypes.h>

cuz < 3 C99.

+1

I , , -. , . .

+1

, (#ifdefs / #pragma ).

, , - .

unit test ( ).

, , , . , : const-correctness, , ..

+1

, , - , , , . , , , , , .

I agree with James - I try very hard not to add functionality to a class that he does not need, most classes do not need a virtual destructor (or a destructor in general). If they do, I wonder why they don't just use smart pointers and other automatic memory management. Obviously, there are many classes (for example, smart locks) that require a destructor, but this is not the only point.

+1
source

All Articles