静态字符数组的对准保障数组、静态、字符

2023-09-11 07:39:51 作者:失心疯

我想知道字符的静态分配阵列的排列保证。综观其他等问题,我发现字符的一些关于动态分配数组。

I want to know the alignment guarantees of a statically allocated array of char. Looking at other SO questions, I found some concerning dynamically allocated arrays of char.

有关静态分配字符阵列,是它们对齐,这样我可以放置新的任何类型到它(只要它足够大)?或者,这是否只适用于动态分配的呢?

For statically allocated char arrays, are they aligned such that I can placement new any type into it (provided it is sufficiently large)? Or does this only apply for dynamically allocated ones?

char buff[sizeof(T)];
T * pT = (T*) buff;
new(pT) T(); // well defined?
...
pT->~T();

如果没有,我怎么能解决这个问题?

If not, how can I overcome this problem?

推荐答案

如果你想保证静态字符数组的对齐方式,可以使用联合的把戏。

If you want to guarantee the alignment of the static char array, you can use the union trick.

union
{
    char buff[sizeof(T)];
    uint64_t dummy;
};

下面的排列将保证在联盟中最大的元素。当然,你应该在一个不错的类包装这个龌龊了。

Here the alignment will be guaranteed for the largest element in the union. And of course you should wrap this nastiness away in a nice class.

编辑:更好的答案:

当然,你会使用的boost :: aligned_storage alignas 的C ++ 11会更好。

Of course you'd be even better using boost::aligned_storage or alignas for C++11.