What are the advantages of boost::noncopyable

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

    A small disadvantage (GCC specific) is that, if you compile your program with g++ -Weffc++ and you have classes containing pointers, e.g.

    class C : boost::noncopyable
    {
    public:
      C() : p(nullptr) {}
    
    private:
      int *p;
    };
    

    GCC doesn't understand what's happening:

    warning: 'class C' has pointer data members [-Weffc++]
    warning: but does not override 'C(const S&)' [-Weffc++]
    warning: or 'operator=(const C&)' [-Weffc++]

    While it won't complain with:

    #define DISALLOW_COPY_AND_ASSIGN(Class) \
      Class(const Class &) = delete;     \
      Class &operator=(const Class &) = delete
    
    class C
    {
    public:
      C() : p(nullptr) {}
      DISALLOW_COPY_AND_ASSIGN(C);
    
    private:
      int *p;
    };
    

    PS I know GCC's -Weffc++ has several issues. The code that checks for "problems" is pretty simplicistic, anyway... sometimes it helps.

提交回复
热议问题