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中更正为MoveInsertable
和DefaultInsertable
.
该vector<T, A>::resize(n)
成员函数需要MoveInsertable
和DefaultInsertable
.这些大致转换为DefaultConstructible
和MoveConstructible
当分配器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的问题中正确演示的那样.
归档时间: |
|
查看次数: |
2963 次 |
最近记录: |