c++ - Is sizeof class guaranteed to contain size of elements only -


this question has answer here:

given example class

class test { public: test(); ~test(); void somemethod(); void someothermethod();  private: int var; }; 

is sizeof(test) == sizeof(int), or cannot make such assumption? platform/compiler dependent?

edit:

motivation read/write class through stream. class indeed contains single integer, convenience access methods - highest order byte of integer reserved flags, 3 lower bytes represent integer 24 bit number. given this, idea write arrays of such class variables, , read them plain int if needed. question quoted having possible answer doesn't address aspect - more padding multiple elements.

in general, no cannot assume size of arbitrary class aggregation of size of it's members. in general, nor should care*. compiler can , change size of classes size is multiple of specific number of bytes. reason improve performance. number of bytes is different every platform.

in specific example, might in fact case sizeof (test) == sizeof (int), doubt real code prompted question.

there ways can ensure does, rely on platform-specific functionality.

first, made sure class pod* , members pods.

second, set packing 1 byte. under both gcc , msvc, instruction similar to:

#pragma pack (1) 

you should turn packing off when not strictly needed, have negative impact on performance:

#pragma pack (push, 1)  class test { public:   void somemethod();   void someothermethod();    int var; };  #pragma pack (pop) 

note above removed private section. class not pod if has nonstatic private or protected data members. removed default constructor , destructor same reason.

under both msvc , gcc, sizeof(test) equal sizeof(int).


pod: plain old datatype. in order class (or struct) pod, must have no user-defined destructor or constructor, copy-assignment operator, , no non-static members of type pointer member. in addition, must have no virtuals, no private or protected non-static members , no base classes. moreover, nonstatic data members have must also pods themselves. in other words, plain old (public) data.


"nor should care." in general, times need make sure size of class size of members @ boundaries of system. example, when moving data in or out of program via socket. compiler pads classes reason. should not override compiler in unless have specific, provable cause.


Comments