应该std :: array有移动构造函数吗? [英] Should std::array have move constructor?

查看:317
本文介绍了应该std :: array有移动构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在std :: array上移动不能有效地执行(O(1)),为什么它有移动构造函数?

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

推荐答案

std :: array 有一个编译器生成的移动构造函数,它允许将一个实例的所有元素移动到另一个实例中。如果元素可以有效移动,或者它们只是可移动的,那么这是方便的。

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);
}

所以我会说 std :: array 应该有一个移动拷贝构造函数,特别是因为它是免费的。没有人会要求它被积极禁用,我看不到任何好处。

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.

这篇关于应该std :: array有移动构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆