We had a problem today when my code generated crazy prices. In the end, I refused that my message classes were the wrong size, even if I pack one byte and run unit tests so that this never happens. (It turns out unit tests did not run under Windows, but this is another problem.)
I have a feature class template that is empty, with the exception of some static const and enum s, and an implementation of the noncopyable class that is empty.
When I get a class from both of the above, the resulting class is padded with 1 byte, but only under Windows, and only if I get both classes. If I get one or the other, the class is not complemented.
I understand that I'm on a platform-specific territory here with #pragma , but it seems strange to me that only during multiple public inheritance does this not do what I expected from him.
Question: why does MSVC set the class to 1 byte in case of multiple open inheritance of empty classes?
Here is the SSCCE that reveals the problem:
#include <cstdlib> #include <string> #include <iostream> using namespace std; #pragma pack (1) template <size_t ExpectedSize> class Traits { public: static const size_t mExpSize = ExpectedSize; }; class noncopyable { public: noncopyable() {}; ~noncopyable() {}; private: noncopyable& operator= (const noncopyable&); noncopyable (const noncopyable&); }; class NotEmpty1 { public: char mBuf [33]; }; class NotEmpty2 : public Traits <33> { public: char mBuf [33]; }; class NotEmpty3 : public noncopyable { public: char mBuf [33]; }; class NotEmpty4 : public Traits <33>, public noncopyable { public: char mBuf[33]; }; int main() { cout << "Case 1: " << sizeof (NotEmpty1) << "\n" << "Case 2: " << sizeof (NotEmpty2) << "\n" << "Case 3: " << sizeof (NotEmpty3) << "\n" << "Case 4: " << sizeof (NotEmpty4) << "\n" ; }
The idea here is that NotEmpty should be exactly 33 bytes for all NotEmpty classes. On Linux (using g ++ 4.4.6.4) they are:
Case 1: 33 Case 2: 33 Case 3: 33 Case 4: 33
On Windows (using MSVC 9 and 10) this is not:
Case 1: 33 Case 2: 33 Case 3: 33 Case 4: 34
Edit: When I use:
#pragma pack (show)
In different places in pf, the compiler always says:
1>main.cpp(57): warning C4810: value of pragma pack(show) == 1
Edit: Display the mBuf offset at the beginning of the class using:
cout << "Offset: " << offsetof(NotEmpty4, mBuf) << "\n";
shows:
Offset: 1