To prohibit copy construction and copy assignment, I've seen the boost noncopyable class and in the Google style guide the DISALLOW_COPY_AND_ASSIGN macro. Is there any reason to prefer one of the techniques over the other, or any subtle differences one should be aware of?
I prefer boost noncopyable over the macro because it's not a macro and it is easier (IMO) to use.
In real code, i'm using neither of them and write the two declarations needed myself.
A subtle difference you might be interested in, though, is that using that macro or your own declarations will not give a compiler error when the class itself tries to copy the object (but rather fail to link later on). noncopyable however will also signal a compiler error in this case, because it's the base-class that has the functions declared private, not the class itself.
Based on the rule of avoid inheritance wherever possible, I always use a macro - in this case my own. Of course, there is the other rule, about avoiding macros...
I always make the copy constructor and assignment operator private, without implementation:
- this prevents someone making copies outside the class (will give compile errors)
- this prevents the class itself also from making copies of itself (will give link errors)
I also add a clear comment (just above the prototypes of the copy constructor and assignment operator) to indicate that I do this to prevent someone making copies (as a reminder to future developers).
In my opinion, this solution is clear, does not rely on external libraries or macro's and is easy to understand.
The two techniques are [practically] the same. One uses a macro to save typing (you still have to place it where you would normally place the code) and the other provides the facility through a base class that you extend.
Avoiding macros is a good thing but extending a class just to avoid placing the copy constructor in the private section of your class seems confusing as a reader.
Any reason you dont just do what these two methods do within your class?
I would never use the DISALLOW_COPY_AND_ASSIGN macro because you have to put it in the private part of the class declaration. What if you (or someone maintaining your code) by mistake put it in the public part? The problem is that it is not obvious at all that "DISALLOW_COPY_AND_ASSIGN" should be put in the private part: the name of the macro seems to imply that it will disallow copy and assignment independently of where you have declared it.
The noncopyable base class avoids this issue entirely.
However, the fastest, most readable, and portable way is to explicitly declare the constructors in the private part of the class.