What are the advantages of boost::noncopyable

前端 未结 11 1211
野性不改
野性不改 2020-11-27 14:10

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

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 14:39

    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

提交回复
热议问题