gpt4 book ai didi

c++ - std::vector::resize(size_type) 是否应该(在 C++11 中)适用于默认的可构造 value_type int[4]?

转载 作者:可可西里 更新时间:2023-11-01 15:18:21 25 4
gpt4 key购买 nike

在 C++11 中,std::vector::resize() 有两个版本:

void resize( size_type count );
void resize( size_type count, const value_type& value);

我理解(正如对 this question 的一个答案的评论之一所建议的那样)第一个要求 value_type 是默认可构造的,而第二个要求它是可复制构造的。但是,(gcc 4.7.0)

using namespace std;
typedef int block[4];
vector<block> A;
static_assert(is_default_constructible<block>::value,";-("); // does not fire
A.resize(100); // compiler error

所以要么我的理解有误,要么 gcc 有问题。哪个?

最佳答案

关于 vector.resize(n) 的要求 (23.3.6.3:10)格式良好的是T应该是 CopyInsertable ,即以下内容应格式正确 (23.2.1:13):

allocator_traits<A>::construct(m, p, v);

哪里A是 vector 的分配器类型,m是分配器,p类型为 T *v类型为 T .

从20.6.8.2:5可以发现,一般情况下这对数组类型是无效的,等同于调用

::new(static_cast<void *>(p))block(v);

对数组类型无效(数组不能用括号初始化)


实际上,您说 g++ 有错误是正确的; CopyInsertable 总是可以解决这个问题 通过提供适当的分配器,但 g++ 不允许这样做:

#include <vector>

template<typename T, int n> struct ArrayAllocator: std::allocator<T[n]> {
void construct(T (*p)[n], T (&v)[n]) {
for (int i = 0; i < n; ++i)
::new(static_cast<void *>(p + i)) T{v[i]};
}
};

int main() {
std::vector<int[4], ArrayAllocator<int, 4>> c;
c.resize(100); // fails

typedef ArrayAllocator<int, 4> A;
A m;
int (*p)[4] = 0, v[4];
std::allocator_traits<A>::construct(m, p, v); // works
}

另一个错误是在标准本身; 20.9.4.3:3 指定 std::is_default_constructible<T>相当于std::is_constructible<T> ,其中 20.9.4.3:6 指定 std::is_constructible<T, Args...>作为 T t(std::declval<Args>()...) 上的良构标准,这对数组类型有效(正如@Johannes Schaub-litb 指出的那样,数组类型可以用 (zero-pack-expansion) 初始化)。但是,17.6.3.1:2 需要 DefaultConstructible另外T()格式正确,数组类型不是这种情况 T但未被 std::is_default_constructible 检查.

关于c++ - std::vector::resize(size_type) 是否应该(在 C++11 中)适用于默认的可构造 value_type int[4]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12192895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com