C ++ Struct - determining the minimum size

Is there a C ++ (or MSVC) way to automatically add structure to the minimum size? For example, imagine the following pseudo-code:

#pragma pad(256) // bytes struct SETUPDATA { int var1; double var2; }; where sizeof(SETUPDATA) = 256 bytes 

The goal is that during development, these members of the structure can change without changing the size of the fingerprint at run time.

+4
source share
3 answers

You can use union

 struct SETUPDATA { union { struct your_data; char [256]; } } 

or something like that. This guarantees at least 256, but only as long as your_dates are no more.

You can also add a simple statement after this, just check the assert(sizeof(struct SETUPDATA) == 256) compiler assert(sizeof(struct SETUPDATA) == 256)

+6
source

One way is to inherit from your "real" structure and use sizeof() to create the augmented structure, for example:

 struct blah_real { int a; }; struct blah : public blah_real { private: char _pad[256 - sizeof(blah_real)]; }; 

You can use #ifdef DEBUG just for this in the debug build and just use the real structure in the release build.

+4
source

The first thing you asked yourself is why your application cares if the struct resized. This indicates the fragility of future changes, and your design can be better served, instead allowing the application to work without problems when changing structural changes.

Perhaps you are trying to serialize the data directly and do not want to deal with changes in the format, but in this case you are already attached to one specific representation of the structure in memory. For example, keep the size of one of the built-in change members due to a compiler update or parameters.

But say you really want to do this.

Just wrap the data in the implant and substitute the real structure:

 struct SetupData { struct Impl { int var1; double var2; }; Impl impl_; unsigned char pad_[256 - sizeof(Impl)]; }; 
+2
source

Source: https://habr.com/ru/post/1484535/


All Articles