Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should std::array have move constructor?

Tags:

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

like image 471
Łukasz Lew Avatar asked Aug 07 '13 13:08

Łukasz Lew


2 Answers

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 <array>
#include <iostream>

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<Foo, 10> a;
  std::array<Foo, 10> 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.

like image 167
juanchopanza Avatar answered Nov 10 '22 15:11

juanchopanza


To summarize and expand on other answers, array<T> should be moveable (when T itself is moveable) because:

  • T may be efficiently moveable.
  • T may be move-only.
like image 28
Herb Sutter Avatar answered Nov 10 '22 14:11

Herb Sutter