Joseph Garvin
Joseph Garvin

Reputation: 21984

Is there any downside to declaring a struct containing a single array as packed?

I have a class that consists internally of just an array, e.g.:

class foo {
public:
    // methods
private:
    int myarray[10];
};

Elsewhere I have a packed struct (GCC extension) that contains a foo:

struct __attribute__((__packed__)) bar {
    foo x;
};

But GCC complains that 'foo' isn't packed, so bar isn't packed. Now, if I make foo packed as well then GCC's error goes away. I intend to use foo in contexts other than being inside packed structs though, so for now I have two versions of foo, Foo and PackedFoo. However, seeing as they each only contain an array, and AFAIK there is no such thing as an 'unpacked array' in C++, is there any harm in me just having Foo and giving it the packed attribute? Will it somehow slow down the code GCC generates when I use Foo outside packed structs?

Upvotes: 0

Views: 220

Answers (1)

ams
ams

Reputation: 25599

If you only have ints (or arrays of ints) in your struct then packing it doesn't make much sense. I'd expect it to be harmless.

Likewise, if you only have foo in bar, then packing that will be pointless. I presume you've simply elided the rest of the contents?

Anyway, the answer to your question is that a packed struct (where packing it did have some effect) will cause the program to run slower. If it didn't, there'd be no point in having 'unpacked' structs. That might not be harmful if it's not in a performance critical section of your program though.

You can't mix and match though - you can't access a struct as packed in one place, and unpacked in another. That just won't work.

It's also unsafe to use packed structs in application APIs or networking, unless you're very sure what it'll do. The layout of packed structs is not standardized, although it's usually quite predictable.

Upvotes: 2

Related Questions