std::vector<type> 的类型要求 [英] type requirements for std::vector<type>
问题描述
我仍然对在 C++11 中与 std::vector
一起使用的类型的要求感到困惑,但这可能是由错误的编译器 (gcc 4.7.0) 引起的.这段代码:
I am still confused about the requirements for a type to be used with a std::vector
in C++11, but this may be caused by a buggy compiler (gcc 4.7.0). This code:
struct A {
A() : X(0) { std::cerr<<" A::A(); this="<<this<<'
'; }
int X;
};
int main()
{
std::vector<A> a;
a.resize(4);
}
工作正常并产生预期的输出,表明调用了默认的构造函数(显式给出)(而不是隐式复制构造函数).但是,如果我向类中添加一个已删除的复制构造函数,即
works fine and produces the expected output, indicating that the default ctor (explicitly given) is called (and not an implicit copy ctor). However, if I add a deleted copy ctor to the class, viz
struct A {
A() : X(0) { std::cerr<<" A::A(); this="<<this<<'
'; }
A(A const&) = delete;
int X;
};
gcc 4.7.0 无法编译,但会尝试使用已删除的 ctor.这是正确的行为还是错误?如果是前者,如何让代码工作?
gcc 4.7.0 does not compile, but tries to use the deleted ctor. Is that correct behaviour or a bug? If the former, how to get the code working?
推荐答案
正如其他人指出的那样,C++11 标准确实需要 CopyInsertable
.然而,这是 C++11 标准中的一个错误.这已在 N3376 到 MoveInsertable
和 DefaultInsertable
.
The C++11 standard does indeed require CopyInsertable
as others have pointed out. However this is a bug in the C++11 standard. This has since been corrected in N3376 to MoveInsertable
and DefaultInsertable
.
vector
成员函数需要 MoveInsertable
和 DefaultInsertable
.当分配器 A
使用默认的 construct
定义时,这些大致转换为 DefaultConstructible
和 MoveConstructible
.
The vector<T, A>::resize(n)
member function requires MoveInsertable
and DefaultInsertable
. These roughly translate to DefaultConstructible
and MoveConstructible
when the allocator A
uses the default construct
definitions.
以下程序使用 clang/libc++ 编译:
The following program compiles using clang/libc++:
#include <vector>
#include <iostream>
struct A {
A() : X(0) { std::cerr<<" A::A(); this="<<this<<'
'; }
A(A&&) = default;
int X;
};
int main()
{
std::vector<A> a;
a.resize(4);
}
对我来说打印出来:
A::A(); this=0x7fcd634000e0
A::A(); this=0x7fcd634000e4
A::A(); this=0x7fcd634000e8
A::A(); this=0x7fcd634000ec
如果删除上面的移动构造函数并用删除的复制构造函数替换它,A
不再是 MoveInsertable
/MoveConstructible
作为移动构造然后尝试使用已删除的复制构造函数,如 OP 问题中正确演示的那样.
If you remove the move constructor above and replace it with a deleted copy constructor, A
is no longer MoveInsertable
/MoveConstructible
as move construction then attempts to use the deleted copy constructor, as correctly demonstrated in the OP's question.
这篇关于std::vector<type> 的类型要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!