I want to set class padding bytes to 0, since I save / load / compare / hash instances at the byte level, and initialized padding with garbage introduces non-determinism in each of these operations.
I know that this will achieve what I want (for trivially copied types):
struct Example { Example(char a_, int b_) { memset(this, 0, sizeof(*this)); a = a_; b = b_; } char a; int b; };
I don’t like to do this for two reasons: I like the constructor initiator lists, and I know that setting bits to 0 does not always coincide with zero initialization (for example, pointers and floats do not necessarily have zero values, all 0 bits).
As an aside, it is clearly limited to the type that can be copied trivially, but this is not a problem for me, since the operations listed above (loading / saving / comparing / hashing at the byte level), in any case, require trivially copied types.
What I would like is something like this [magic] snippet:
struct Example { Example(char a_, int b_) : a(a_), b(b_) { // Leaves all members alone, and sets all padding bytes to 0. memset_only_padding_bytes(this, 0); } char a; int b; };
I doubt that such a thing is possible, therefore, if someone can offer a non-ugly alternative ... I'm all ears :)
c ++ padding
Ben hymers
source share