Should std::array have move constructor?

前端 未结 3 2004
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-18 20:33

Moving can\'t be implemented efficiently (O(1)) on std::array, so why does it have move constructor ?

3条回答
  •  走了就别回头了
    2021-02-18 21:27

    std::array has a compiler generated move constructor, which allows all the elements of one instance to be moved into another. This is handy if the elements are efficiently moveable or if they are only movable:

    #include 
    #include 
    
    struct Foo
    {
      Foo()=default;
      Foo(Foo&&)
      {
        std::cout << "Foo(Foo&&)\n";
      }
      Foo& operator=(Foo&&)
      {
        std::cout << "operator=(Foo&&)\n";
        return *this;
      }
    };
    
    int main()
    {
      std::array a;
      std::array b = std::move(a);
    }
    

    So I would say std::array should have a move copy constructor, specially since it comes for free. Not to have one would require for it to be actively disabled, and I cannot see any benefit in that.

提交回复
热议问题