删除复制构造函数的通用宏,给定类的赋值运算符

有没有办法创建一个通用宏来删除复制构造函数,赋值运算符

    //Below two lines are class specific, and looking to replace with some generic way
    //without mentioning hardcoded class name
    #define NO_COPY             Original(_In_ const Original&) = delete;
    #define NO_ASSIGNMENT       Original& operator=(_In_ const Original&) = delete;
    
    //simple class
    class Original
    {
    public:
        NO_COPY;
        NO_ASSIGNMENT;
    };

回答

boost::noncopyable是这样:

  class noncopyable
  {
  protected:
#if !defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS) && !defined(BOOST_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS)
      BOOST_CONSTEXPR noncopyable() = default;
      ~noncopyable() = default;
#else
      noncopyable() {}
      ~noncopyable() {}
#endif
#if !defined(BOOST_NO_CXX11_DELETED_FUNCTIONS)
      noncopyable( const noncopyable& ) = delete;
      noncopyable& operator=( const noncopyable& ) = delete;
#else
  private:  // emphasize the following members are private
      noncopyable( const noncopyable& );
      noncopyable& operator=( const noncopyable& );
#endif
  };

用法是

struct X : private boost::noncopyable {};

如果您不想要 boost,那么编写自己的my::noncopyable. 该protected构造函数和析构函数仅仅是明确指出,该类意味着作为基类。没有 C++11 之前的条件,该类只是:

  class noncopyable
  {
  protected:
      constexpr noncopyable() = default;
      ~noncopyable() = default;
      noncopyable( const noncopyable& ) = delete;
      noncopyable& operator=( const noncopyable& ) = delete;
  };

您要求的宏不存在。正如 Sergey 在评论中指出的那样,您至少必须将类的名称传递给宏,这使得键入的意义不那么重要。

最后但并非最不重要的一点是,我建议您阅读这个答案,它对noncopyable基类和拼写已删除的成员函数提出了一些好处。不要试图变得太懒惰。少打字并不总是让代码更干净的方法。


以上是删除复制构造函数的通用宏,给定类的赋值运算符的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>