Alignment guarantees of static char array

前端 未结 3 1715
长情又很酷
长情又很酷 2020-12-18 08:48

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 ar

3条回答
  •  被撕碎了的回忆
    2020-12-18 09:23

    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.

    Edit: better answer:

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

提交回复
热议问题