c++boostnoncopyable

What are the advantages of boost::noncopyable


To prevent copying a class, you can very easily declare a private copy constructor / assignment operators. But you can also inherit boost::noncopyable.

What are the advantages / disadvantages of using boost in this case?


Solution

  • Summarizing what others have said:

    Advantages of boost::noncopyable over private copy methods:

    1. It is more explicit and descriptive in the intent. Using private copy functions is an idiom that takes longer to spot than noncopyable.
    2. It is less code / less typing / less clutter / less room for error (the easiest would be accidentally providing an implementation).
    3. It embeds meaning right in the type's metadata, similar to a C# attribute. You can now write a function which accepts only objects which are noncopyable.
    4. It potentially catches errors earlier in the build process. The error will be presented at compile-time rather than link-time, in the case that the class itself or friends of the class are doing the erroneous copying.
    5. (almost the same as #4) Prevents the class itself or friends of the class from calling the private copy methods.

    Advantages of private copy methods over boost::noncopyable:

    1. No boost dependency