std :: array是否可以移动?

Ale*_*tto 35 c++ arrays move-semantics c++11

std :: array是否可以移动?

Bjarne Native 2012演示幻灯片(幻灯片41)中,它std::array列为唯一不可移动的容器之一.

快速浏览gcc 4.8库源代码似乎证实std::array不可移动:

的std ::向量:

/* @brief  %Vector move constructor.
   ...       */
  vector(vector&& __x) noexcept
  : _Base(std::move(__x)) { }
Run Code Online (Sandbox Code Playgroud)

在std :: array中,接收rvalue引用参数的唯一方法是随机元素访问,这避免了通过复制返回:

get(array<_Tp, _Nm>&& __arr) noexcept
    { /*...*/ return std::move(get<_Int>(__arr)); }
Run Code Online (Sandbox Code Playgroud)

是否std::array创建了默认的move-constructor和move-assignment ,或者是std::array不可移动的?如果它是不可移动的,为什么std::array不能移动std::vector呢?

Pot*_*ter 46

std::array 只有当其包含的物体可移动时才可移动.

std::array与其他容器完全不同,因为容器对象包含存储,而不仅仅是指向堆的指针.移动一个std::vector只复制一些指针,并且包含的​​对象不是更明智的.

是的,std::array使用默认的移动构造函数和赋值运算符.作为聚合类,不允许定义任何构造函数.

  • @SethCarnegie它移动构造成员数组,它移动每个元素. (10认同)
  • @AlessandroStamatto虽然O(n)你仍然可以从单个元素的运动中获利.所以一般来说,移动`std :: array <std :: string>`应该比复制它更好. (7认同)
  • 谢谢!因此,std :: array中的移动操作是O(n),因为移动实际上发生在其元素上,而在std :: vector中它将是O(1)?(因为在std :: vector情况下只需要移动指针) (3认同)
  • @balki`memcpy`仍然是O(n). (3认同)
  • 数组的默认移动构造函数会移动每个元素吗? (2认同)