Sometimes in C++ it can be an advantage for making a class non-copyable for
various reasons. This can be accomplished by inheriting a class from the boost
libraries. Which is called boost::noncopyable. This will force the classes copy
constructors to be private.

class MyClass : private boost::noncopyable
{
        public:
                MyClass() { }
};

By doing this. It will prevent the following from being able to compile because a copy is passed to the function. A reference should be passed instead. This will also prevent operations such as "a = b".

void func(MyClass a)
{

}

int main(int argc, char **argv)
{
        MyClass a, b;

        func(a);

        return 0;
}

Some advantages of using this include.

  • boost::noncopyable prevents the classes methods from accidentally using the private copy constructor
  • It is more explicit and descriptive in the intent. Using private copy functions is an idiom that takes longer to spot than non-copyable.
  • It is less code / less typing / less clutter / less room for error (the easiest would be accidentally providing an implementation).
  • You don't have to write your own private copy constructor.
  • Attempting to copy will catch issues sooner. eg at compile time.

One disadvantage is that there is a small overheat of the class inheritance.





Last Modified: 18 February 2017

Releated Posts


2017-04-25 - Linux Programming - Signals the easy way
2017-03-01 - Shooting yourself in the head with threads
2013-08-22 - CPP - Prevent an object by being copied with boost::noncopyable
2013-03-29 - CPP - Why you need a copy constructor
2013-03-27 - CPP -boost::optional
2012-11-06 - C++ - Stringstream example
2012-08-09 - C++ - Check an IP Address is in a IP Mask
2012-06-30 - CPP - Creating A basic python wrapper
2012-06-16 - CPP - Using gperf
2012-05-10 - CPP - Optional function arguments
2012-03-19 - CPP - Read / Write std::map to a file.