Most concise way to disable copying class in C++11

后端 未结 4 1002
日久生厌
日久生厌 2021-02-05 08:28

I have a problem dealing with deprecated since C++11 default generation of copy constructor and copy assignment operator when there is a user-defined destructor.

For mos

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 08:51

    1. Only copy constructor and copy assignment operator will be generated when destructor is explicitly defaulted. And even then their generation is deprecated. So, in order to have virtual destructor and all default methods, one should write the following:

      struct Base
      {
          Base()=default;
          virtual ~Base() = default;
          Base(const Base&)=default;
          Base& operator=(const Base&)=default;
          Base(Base&&)=default;
          Base& operator=(Base&&)=default;
      };
      

      I would definitely use a macro for more than one such Base class.

    2. In case when destructor is defined by user, 2 special methods are still generated. There are the following ways to disable deprecated generating copy constructor and copy assignment operator:

      • delete move constructor OR move assignment operator (not quite self-explanatory but very short):

        Base(Base&&)=delete; // shorter than deleting assignment operator
        
      • delete both copy constructor and copy assignment operator:

        Base(const Base&)=delete;
        Base& operator=(const Base&)=delete;
        

      Note that you have to explicitly declare default constructor if you need it, e.g. Base()=default;.

      Macro or inheriting special class can be used as well for this purpose but I personally prefer deleting move constructor to implementing my own macro or base class. When using Qt or boost, I would prefer Q_DISABLE_COPY(Base) and inheriting boost::noncopyable respectively, because they are already implemented, widely known and recognizable.

    http://accu.org/index.php/journals/1896 - detailed explanation and rationale for these issues.

提交回复
热议问题