Compiling this header:

// myheader.h

class MyClass {

    MyClass();
    ~MyClass();

    unsigned int mMyUint;
    bool bMyBool;
    std::string sMyString;
};

with Visual Studio 2010 /W4 (I was told to do so), target x64, gives me the following warning C4121:

'MyClass' : alignment of a member was sensitive to packing, referring to line where the std::string sMyString is. The official help of Microsoft proposes to use a #pragma pack(x), where x be 1, 2, 4 dependent on the members one uses inside its struct / class.

No I wonder which alignment to use for std::string? My idea was that std::string is nor compiler neither platform independent. Is there any way to resolve that issue especially considering the other members which may have any other aligment?

Best would be a compiler-independent (and even portable) solution.

Update: Concerning the very useful answer provided by jalf: No, in this file I am not using a #pragma pack(x). I used it in another struct where I use Bit-fields which I have seen are padded when not using the #pragma pack(x). Now I was just alarmed to run into the same trap because I did not know how the Microsoft compiler resolves std::string.

有帮助吗?

解决方案

The compiler-independent and portable solution is exactly the code that you have shown us. The compiler takes care of aligning everything correctly if you don't do anything to disrupt it. (such as using SIMD types which require special alignment, or using #pragma pack)

If you're using a #pragma pack, then:

  1. why didn't you show us?
  2. don't.

If the code you have shown us gives you any warnings at /W4, blame Microsoft. The code is correct, portable and safe (unlike code which uses the pack pragma).

Microsoft has some weird ideas about warnings at /W4. Most compilers only issue warnings for things that look like they might contain errors.

Microsoft has a whole load of warnings basically saying "I have no reason to suspect that there is a problem with this code, but if you had written it differently, it might contain a bug", which is pure nonsense.

With other compilers I generally recommend compiling with all warnings enabled. On Microsoft's compiler, that's not really viable. (Although you can use /W4, and selectively silence specific nonsense warnings)

What I think they're specifically telling you is that the structure contains padding bytes (and so, if you did use #pragma pack, it would alter the layout of the class, and one of the affected class members would be "sensitive" to this change).

If possible, consider rearranging the class members so they are listed in descending order of size. That gives you more compact class layouts, with padding (if any) only at the end of the class.

But there is nothing wrong with the class definition you're currently using.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top