views:

57

answers:

2

First: is it boost::noncopyable or booster::noncopyable. I have seen both in different places.

Why would one want to make a class noncopyable? Can you give some sample use cases?

+1  A: 

The right one in the case of boost is boost::noncopyable.

It is used to prevent copying of objects like the name tells. It makes sense where copying leads to a very difficult to handle situation. An example is a class wrapping the concept of file handle or network connection like stated in the documentation. The problems arise with freeing/closing the resource or file. If you have many copies of them how would you handle it. You could use some reference counting but it is difficult to handle correctly if you unwrap the handles at some places...

Personally I find its most clear and useful usage in implementing a singleton pattern, where you really want to have only one instance, that in this case you obviously do not want to be copyable. Singletons ensure only one instance of a class can be created for holding some global resources for example a system configuration.

jdehaan
+1  A: 

I find it useful whenever you have a class that has a pointer as a member variable which that class owns (ie is responsible for destroying). Unless you're using shared_ptr<> or some other reference-counted smart pointer, you can't safely copy or assign the class, because in the destructor you will want to delete the pointer. However, you don't know if a copy of the class has been taken and hence you'll get either a double-delete or access violation from dereferencing a freed pointer.

If you inherit from noncopyable then it has two benefits:

  • It prevents the class from being copied or assigned
  • It makes the intention clear from looking at the class definition, ie self-documenting code

eg

class MyClass : boost::noncopyable
{ 
   ...
};
the_mandrill