Is declaring explicitly defaulted move constructor in every class that doesn't provide user-defined one a good practice?

不想你离开。 提交于 2019-12-12 22:13:20

问题


There are quite complex (for me) rules that define when implicitly defaulted move constructor is generated and when it is not generated. What I'm afraid of is that the default move constructor won't be generated. Also I'm afraid that I (or someone else) modify the class in the future and implicit move constructor will disappear.

There is an "advice" that says "you can always explicitly invoke the default generation for functions that can be automatically generated with = default (that's what the syntax is for)". And now I'm asking: is it a good idea? Are there any reasons not to do this? I guess if there were no problems with that then we would not need defaulted move constructors, move constructors would just always be generated. But since the Standard defines such strict rules, there probably are reasons for doing that.


回答1:


Consider the following scenario. You have a class that is fine with auto-generated move constructor and destructor:

class X {
      int i_;
   public:
      X(int i) : i_(i) { }
};

Then, in the future, you add a member variable, that requires user-defined copy constructor and destructor:

class X {
      int i_;
      char* buf_;
      size_t n_;
   public:
      X(int i, size_t n) : i_(i), n_(n), buf_(new char[n]) { }
      X(const X& o) : i_(o.i_), n_(o.n_), buf_(new char[o.n_]) { memcpy(buf_, o.buf_, n); }
      ~X() { delete[] buf_; }
};

If move constructor would be defaulted here, the new class version would be wrong.

Without defaulted move constructor, modified class is fine according to rules-of-five which says, that if one of the 5 special function is required to be user-defined, the others are likely required to be user-defined as well. You are now forced to define move constructors manually, if you need it.



来源:https://stackoverflow.com/questions/49003289/is-declaring-explicitly-defaulted-move-constructor-in-every-class-that-doesnt-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!