形式上,struct 可能有填充,使其大小大于 1。
也就是说,正式地你不能reinterpret_cast 并且拥有完全可移植的代码,除了¹只有一个项目的数组。
但是在实践中,几年前有人问现在是否有任何编译器默认情况下会为struct T{ char x; }; 提供sizeof(T) > 1。我还没有看到任何例子。因此,在实践中,只需 static_assert 大小为 1,完全不用担心 static_assert 在某些系统上会失败。
即,
S const a1[] = { {'a'}, {'4'}, {'2'}, {'\0'} };
static_assert( sizeof( S ) == 1, "!" );
char const* const a2 = reinterpret_cast<char const*>( a1 );
for( int i = 0; i < 4; ++i )
{
assert( a1[i].v == a2[i] );
}
由于可能以索引具有未定义行为的方式解释 C++14 及更高版本的标准,基于对“数组”的特殊解释,即指代某个原始数组,一个可能会以更笨拙和冗长但保证有效的方式编写此代码:
// I do not recommend this, but it's one way to avoid problems with some compiler that's
// based on an unreasonable, impractical interpretation of the C++14 standard.
#include <assert.h>
#include <new>
auto main() -> int
{
struct S
{
char v;
};
int const compiler_specific_overhead = 0; // Redefine per compiler.
// With value 0 for the overhead the internal workings here, what happens
// in the machine code, is the same as /without/ this verbose work-around
// for one impractical interpretation of the standard.
int const n = 4;
static_assert( sizeof( S ) == 1, "!" );
char storage[n + compiler_specific_overhead];
S* const a1 = ::new( storage ) S[n];
assert( (void*)a1 == storage + compiler_specific_overhead );
for( int i = 0; i < n; ++i ) { a1[i].v = "a42"[i]; } // Whatever
// Here a2 points to items of the original `char` array, hence no indexing
// UB even with impractical interpretation of the C++14 standard.
// Note that the indexing-UB-free code from this point, is exactly the same
// source code as the first code example that some claim has indexing UB.
char const* const a2 = reinterpret_cast<char const*>( a1 );
for( int i = 0; i < n; ++i )
{
assert( a1[i].v == a2[i] );
}
}
注意事项:
¹ 该标准保证struct 的开头没有填充。