我仍然对 的行为感到困惑std::vector::resize()
。考虑以下代码(另请参阅std::vector 的类型要求 https://stackoverflow.com/questions/12251368/type-requirements-for-stdvectortype)
struct A {
A() : X(0) { std::cerr<<" A::A(); this="<<this<<'\n'; }
A(A const&) { assert(0); } // is required but doesn't fire in vector::resize
int X;
};
int main()
{
std::vector<A> a;
a.resize(4); // would not compile without A::A(A const&) or A::A(A&&)
}
Without A::A(A const&)
or A::A(A&&)
,该线与a.resize(4);
不编译。但是,该构造函数从未被调用:assert(0)
不火!有人可以向我解释一下吗?
我的解释是,模板魔术需要这些构造函数中的任何一个的存在allocator_traits<>
(由std::vector::resize()
),但实际上从未被调用过。但是,如果您不调用某个方法,为什么还需要该方法的存在呢?
该标准最新修订版(n3376 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3376.pdf) says:
12 - If size() < sz
,
追加sz - size()
默认插入到序列中的元素。
13 - 要求:T
应该MoveInsertable
and DefaultInsertable
into *this
.
其含义是MoveInsertable
可能发生的任何重新分配都需要,而DefaultInsertable
是实际附加所必需的。因此,仅当您的向量已包含元素并且需要重新分配时,您的复制或移动构造函数才会触发。
事实上,如果我们写:
std::vector<A> a;
a.resize(1);
assert(!a.empty() && a.capacity() < 4);
a.resize(4);
然后是复制或移动构造函数A
被调用,并且您的断言被触发。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)