为什么一个使用迭代器的构造函数要求元素是EmplaceConstructable

Why does a constructor which takes iterators require elements to be EmplaceConstructible?

本文关键字:构造函数 元素 EmplaceConstructable 迭代器 一个 为什么      更新时间:2023-10-16

我在标准(n4296),23.2.3/4(表100)中看到了对序列stl容器的要求,并读到了一个采用参数迭代器(X-容器,I和j-输入迭代器)的构造函数

X(i, j)
X a(i, j)

要求容器的元素类型为EmplaceConstructable。

Requires: T shall be EmplaceConstructible into X from *i

我认为构造函数可以通过为范围内的每个迭代器调用std::allocater_traits::construct(m,p,*it)方法来实现(其中m-类型为a的分配器,p-指向内存的指针,it-[I;j中的迭代器),并且元素只需要CopyInsertable概念,因为只提供了一个参数用于复制/移动,而EmplaceConstructable概念要求元素从一组参数中构造。做出这个决定有什么理由吗?

CopyInsertable是一个二进制概念-给定容器X,它应用于单个类型T,该类型需要有一个复制构造函数。然而,*i可以是与T不同的类型,只要有一种方法可以从*i:(隐式)构造T

  char s[] = "hello world!";
  std::vector<int> v(std::begin(s), std::end(s));
  // int is EmplaceConstructible from char

一个(人为的)例子,其中T而不是CopyInsertable:

struct nocopy {
  nocopy(int) {}
  nocopy(nocopy const&) = delete;
  nocopy(nocopy&&) = delete;
};
int a[]{1, 2, 3};
std::vector<nocopy> v(std::begin(a), std::end(a));
相关文章: