Deleting copy constructor breaks inherited constructors

后端 未结 3 1587
有刺的猬
有刺的猬 2021-02-19 19:41

I am trying to use the constructor inheritance feature of C++11. The following snippet (copied from somewhere, I don\'t remember whence) works completely fine:

#         


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-02-19 20:02

    Inheriting constructors doesn't get the special constructors -- empty, copy, move. This is because what you are asking for literally is almost always a bad idea.


    Examine:

    struct base {
      std::vector data;
      base(base const&)=default;
      base(base&&)=default;
      base(size_t n):data(n) {}
      base()=default;
    };
    
    struct derived:base {
      using base::base;
      std::vector more_data;
    };
    

    do you really want derived(base const&) to exist? Or base(base&&)? Both would hopelessly slice derived.

    The danger of those operations happening "accidentally" means you have to bring them in explicitly if you want them.


    The copy/move/default ctors, by default, happen to just call the parent version, plus the ctors of member variables. There is no need (usually) to involve inheriting them from your parent.

    However, once you =delete, =default or define one of these special ctors, the other ones stop being generated by the compiler. So you have to =default the other ones, if you still want them to stick around.

提交回复
热议问题