在以下代码中,从vector<int>
数组构造int8_t
。它碰巧可以工作,但是安全吗?
int8_t *arr;
int arr_size;
... // Filling the array somehow
std::vector<int> v(arr, arr + arr_size); // Is this safe even though we use int8_t* to construct a vector of int?
cppreference.com上的文档说:
这种解释没有给我关于我的问题的线索。实际上,这进一步使我感到困惑,因为静态类型转换的模板参数似乎非常错误。
最佳答案
您使用的 vector 构造函数是通过类似于copy algorithm的方式实现的。
template<class InputIt, class OutputIt>
OutputIt copy(InputIt first, InputIt last,
OutputIt d_first)
{
while (first != last) {
*d_first++ = *first++;
}
return d_first;
}
如果两种类型的大小相同,则编译器可以进一步优化并使用
memcpy()
。但是,此优化发生在较低的级别,这可能会使您认为它可能会失败。所需的两件事是需要匹配输入和输出容器的长度(在您的情况下自动完成)以及需要编译
*d_first++ = *first++;
。因此,如果您的类型不同,则可能需要声明一个赋值运算符。关于c++ - 根据较小类型的指针定义的范围构造 vector ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49089168/