std :: vector <type>的类型要求

Wal*_*ter 2 c++ constructor allocation stdvector c++11

我仍然对std::vector在C++ 11中使用的类型的要求感到困惑,但这可能是由错误的编译器(gcc 4.7.0)引起的.这段代码:

struct A {
  A() : X(0) { std::cerr<<" A::A(); this="<<this<<'\n'; }
  int X;
};

int main()
{
  std::vector<A> a;
  a.resize(4);
}
Run Code Online (Sandbox Code Playgroud)

工作正常并产生预期的输出,表明默认的ctor(显式给定)被调用(而不是隐式复制ctor).但是,如果我将删除的副本ctor添加到课程中,即

struct A {
  A() : X(0) { std::cerr<<" A::A(); this="<<this<<'\n'; }
  A(A const&) = delete;
  int X;
};
Run Code Online (Sandbox Code Playgroud)

gcc 4.7.0不编译,但尝试使用已删除的ctor.这是正确的行为还是错误?如果是前者,如何让代码工作?

How*_*ant 13

CopyInsertable正如其他人所指出的那样,C++ 11标准确实需要.但是,这是C++ 11标准中的一个错误.此后在N3376中更正为MoveInsertableDefaultInsertable.

vector<T, A>::resize(n)成员函数需要MoveInsertableDefaultInsertable.这些大致转换为DefaultConstructibleMoveConstructible当分配器A使用默认construct定义时.

以下程序使用clang/libc ++编译:

#include <vector>
#include <iostream>

struct A {
  A() : X(0) { std::cerr<<" A::A(); this="<<this<<'\n'; }
  A(A&&) = default;
  int X;
};

int main()
{
  std::vector<A> a;
  a.resize(4);
}
Run Code Online (Sandbox Code Playgroud)

并打印出来:

 A::A(); this=0x7fcd634000e0
 A::A(); this=0x7fcd634000e4
 A::A(); this=0x7fcd634000e8
 A::A(); this=0x7fcd634000ec
Run Code Online (Sandbox Code Playgroud)

如果删除上面的移动构造函数并将其替换为已删除的复制构造函数,A则不再MoveInsertable/ MoveConstructible作为移动构造然后尝试使用已删除的复制构造函数,正如OP的问题中正确演示的那样.