Dmitry Dmitry - 3 months ago 17
C++ Question

How does boost::noncopyable work

I've stumbled upon 2 stupid questions during my C++ practixe :

  1. AFAIK in c++ copy constructor and assignment operators are not how does boost::noncopyable help in this case to prohibit this stuff?

    class X: private boost::noncopyable
    Is it necessary to use only private inheritance to achieve the goal?

  2. Is there only 1 way to declare assignment operator

    MyClass& operator= ( const MyClass & );
    Is it the same thing to declare

    void operator= ( const MyClass & );

    const MyClass& operator= ( const MyClass & );


The non-copyable in C++11 and later will work by declaring it =delete, preferably public. However, before C++11 this was not possible and the combination of 2 techniques are being used:

  • Declare the method private
  • Don't implement the method

By making the method private, this cannot be called by non-friend classes. As a result, any code trying to call this will result in a compilation error.

In practice, the class can still copy itself. Therefore this method does not get implemented and you will get a linker error.

Inheriting from boost::noncopyable will prevent the second use case, however, it also prevents that the compiler can generate a valid default copy constructor ... as they will violate the previous constraints.

Note that if you really want, you can write copy constructors for the inheriting class by calling the normal constructors of these 'non-copyable' classes.

For your second question: Yes, you can give it whatever return type you want, though you can't write a = b = c; anymore.