这是使用std :: array未定义的行为吗? [英] Is this use of std::array undefined behavior?
问题描述
可能重复:
允许使用`char *`进行别名`T *`。
Possible Duplicate:
Aliasing `T*` with `char*` is allowed. Is it also allowed the other way around?
我使用的是 std :: array
of char
用于保存未知原始类型的值,长度不超过10个字节,像这样:
I'm using a std::array
of char
s to hold a value of unknown primitive type, which is no more than 10 bytes long, like so:
std::array<char, 10> val;
*reinterpret_cast<double*>(val.data()) = 6.3;
//blah blah blah...
double stuff = *reinterpret_cast<double*>(val.data());
我已经读过通过 char *
未定义,因为编译器假设 char *
可以别名任何类型的值。当值放在(我假设是)数组 char
在对象内时,这仍然工作?
I have read that casting back and forth through char *
is not undefined, because the compiler assumes a char *
may alias a value of any type. Does this still work when the value is placed in (what I assume is) an array of char
s inside the object?
注意:我知道我可以在这里使用联合,但这将导致大量的样板代码,我正在做什么,我想避免它,如果必要,因此的问题。 p>
Note: I am aware that I could be using a union here, but that would result in a large amount of boilerplate code for what I am doing, and I would like to avoid it if necessary, hence the question.
推荐答案
是的, std :: array< char,10>
不满足 double
的对齐要求,因此 reinterpret_cast
UB。
Yes, std::array< char, 10 >
does not satisfy the alignment requirements of double
so that reinterpret_cast
provokes UB.
请尝试 std: :aligned_storage
。
这篇关于这是使用std :: array未定义的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!