开发者

Is there a guarantee as to the size of a class that contains an array?

开发者 https://www.devze.com 2023-01-14 18:06 出处:网络
Given: templ开发者_开发技巧ate <int N> struct val2size { char placeholder[N]; }; Is there any guarantee that sizeof(val2size<N>) == N?The only guarantee is that

Given:

templ开发者_开发技巧ate <int N>
struct val2size
{
    char placeholder[N];
};

Is there any guarantee that sizeof(val2size<N>) == N?


The only guarantee is that

sizeof(val2size<N>) >= N

There may be unnamed padding at the end of the struct. I don't think it's likely that there will be unnamed padding, but it's possible.


No, James covers that. But you can get what you want with:

template <std::size_t N> // not an int, a negative value doesn't make sense
struct value_to_size
{
    typedef char type[N];
};

sizeof(value_to_size<N>::type) is guaranteed to be N. (This trick can be used to make a compile-time size-of array utility.)


By default, there is no guarantee because of possible padding. However, many compilers (at least VC++ and gcc) allow you to set the alignment of structures using a pragma, like this:

#pragma pack(push, 1)
template <int N>
struct val2size
{
    char placeholder[N];
};
#pragma pack(pop)

Setting the alignment to 1 essentially prevents any additional padding at the end of the structure.


It depends on the size of N actually and whether that size of N char can be fit in a world align manner. If the memory of character array is world align ( 4 byte align for 32 bit and 8 byte align for 64 bit) then you will get sizeof==N or if not then it will add padding to make the memory allocated to be world align and in that case it will be >=N.

0

精彩评论

暂无评论...
验证码 换一张
取 消