我可以投一个std ::数组切片?或者是有什么我可以用呢? [英] Can I cast a std::array to slice? Or is there anything else I can use instead?
问题描述
这是不确定的行为?
std::array<int, 5> x = {3, 5, 1, 2, 3};
std::array<int, 3>& y = *reinterpret_cast<std::array<int, 3>*>(&x[1]);
for(int i = 0; i != 3; i++) {
std::cout << y[i] << "\n";
}
也许是的,但我真的觉得应该有一个安全办法切片的std ::阵列
秒。
编辑:以下拉狄克的建议:
template<unsigned N, unsigned start, unsigned end, typename T>
std::array<T, end - start>& array_slice(std::array<T, N>& x)
{
static_assert(start <= end, "start <= end");
static_assert(end <= N-1, "end <= N");
return *reinterpret_cast<std::array<T, end - start>*>(&x[start]);
}
编辑:确定,我决定,我很不满意的std ::阵列
和将移动到别的东西,任何想法?
Ok, I decided that I'm unhappy with std::array
s and will move to something else, any ideas?
推荐答案
是的,这是不确定的行为。你把同一类型和 reinter pret_cast
ING到另一个。事实上,使用 reinter pret_cast的
应该是一个大红旗此处有怪物!
Yes, that is undefined behavior. You're taking one type and reinterpret_cast
ing it to another. Indeed, the use of the reinterpret_cast
should be a big red flag for "here there be dragons!"
对于数组切片,这是不会发生的。 A 的std ::阵列
包含的值;这片将包含的引用的该阵列的一部分。因此,它不会是一个的std ::阵列
。你可以的复制的阵列的片,但不能使用的std ::阵列
。您需要使用的std ::矢量
,因为它允许构造函数从一个值范围的通话,以及建筑。记住:的std ::阵列
只是围绕一个C数组一个更好的包装
As for slicing arrays, that's not going to happen. A std::array
contains values; a slice of this would contain references to part of that array. And therefore, it would not be a std::array
. You can copy slices of arrays, but not using std::array
. You would need to use std::vector
, since it allows the calling of constructors, as well as construction from a range of values. Remember: std::array
is just a nicer wrapper around a C-style array.
该委员会正在研究的模板 ARRAY_REF&LT; T&GT;
类,而这正是它说:到类型的数组中某一段参考 T
。这可能是一个常规的C风格的数组,的std ::矢量
,一个的std ::阵列
,或者只是一些内存分配与新T []
。有的类已经的一些库实现,但没有什么是尚未标准化。
The committee is looking into a template array_ref<T>
class, which is exactly what it says: a reference to some segment of an array of type T
. This could be a regular C-style array, a std::vector
, a std::array
, or just some memory allocated with new T[]
. There are some library implementations of the class already, but nothing is standardized yet.
继拉狄克的建议:
躲在一个函数未定义行为的不让它定义的行为的。你可以尝试pretend它不是不确定的,但它仍然是。那一刻您使用 reinter pret_cast
,你心甘情愿地放弃生活在C ++ - 土地
Hiding the undefined behavior in a function does not make it defined behavior. You can try to pretend that it isn't undefined, but it still is. The moment you use that reinterpret_cast
, you willingly give up living in C++-land.
这篇关于我可以投一个std ::数组切片?或者是有什么我可以用呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!