What are the advantages of boost::noncopyable

前端 未结 11 1219
野性不改
野性不改 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:36

    I'd rather use boost::noncopyable than manually delete or privatize the copy constructor and assignment operator.

    However, I almost never use either method, because:

    If I am making a non-copyable object, there has to be a reason it is non-copyable. This reason, 99% of the time, is because I have members that can't be copied meaningfully. Chances are, such members would also be better suited as private implementation details. So I make most such classes like this:

    struct Whatever {
      Whatever();
      ~Whatever();
      private:
      struct Detail;
      std::unique_ptr detail;
    };
    

    So now, I have a private implementation struct, and since I've used std::unique_ptr, my top-level class is non-copyable for free. The link errors that come from this are understandable because they talk about how you can't copy a std::unique_ptr. To me, this is all the benefits of boost::noncopyable and a private implementation rolled into one.

    The benefit with this pattern is later, if I decide that I did indeed want to make my objects of this class copyable, I can just add and implement a copy constructor and/or assignment operator without changing the class hierarchy.

提交回复
热议问题