静态字符数组的对准保障 [英] Alignment guarantees of static char array

查看:136
本文介绍了静态字符数组的对准保障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于静态字符数组的对准保障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆