Search code examples
c++boostnoncopyable

What are use cases for booster::noncopyable?


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?


Solution

  • 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
    { 
       ...
    };