Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inheritance and attribute packed

Tags:

c++

g++

clang++

Consider this code in C++

struct Base
{
   std::int64_t x;
   std::int64_t y;
};
static_assert(sizeof(Base) == 16, "Base not of size 16!");

struct Derived : Base
{
   std::int32_t z;
}__attribute__((packed));
static_assert(sizeof(Derived) == 20, "Derived not of size 20!");

clang considers this code valid, where as gcc results in firing of the second static_assert. ("Derived not of size 20!). If I add attribute packed in Base as well, then it is fine in both the compilers. Does anyone know which one is right and why?

like image 861
skgbanga Avatar asked Sep 02 '16 23:09

skgbanga


People also ask

What does attribute packed mean?

__attribute__((packed)) variable attribute The packed variable attribute specifies that a variable or structure field has the smallest possible alignment. That is, one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute.

What is __ attribute __ (( packed ))?

4.11 The __packed__ Attribute This attribute, attached to struct or union type definition, specifies that each member (other than zero-width bitfields) of the structure or union is placed to minimize the memory required. When attached to an enum definition, it indicates that the smallest integral type should be used.

What is__ packed in C?

The __packed qualifier sets the alignment of any valid type to 1. This means that: There is no padding inserted to align the packed object.


1 Answers

Both are right.

The compiler is allowed to add padding to your class (between members and at the end) and it is implementation defined whether it does or not, so your static_assert's are basically testing something that depends on the compiler (and platform) used - thus they are not portable and you can't expect the same result everywhere.

Your use of __attribute__((packed)) basically tells the compiler(s) who understand the attribute, that you want a specific behaviour rather than what it would do by default. This may generate the result you want in this case, but it also has implications (memory layout/use and on some CPUs performance). And you still can't be certain that all compilers will do the same.

like image 149
Jesper Juhl Avatar answered Sep 27 '22 20:09

Jesper Juhl