4

有一些非常奇怪的问题,作为 c++ 的初学者,我不知道为什么。

struct DeviceSettings
{
public:
....somevariables
    DXSize BackbufferSize;

....somemethods
};

struct DXPoint;
typedef DXPoint DXSize;

__declspec(align(16)) struct DXPoint
{
public:
    union
    {
        struct
        {
            int x;
            int y;
        };
        struct
        {
            int width;
            int height;
        };
        int dataint[2];
        __m128i m;
    };

    DXPoint(void);
    DXPoint(int x, int y);
    ~DXPoint(void);

    void operator = (const DXPoint& v);
};

出于某种原因,当我声明 DeviceSettings 时,应用程序崩溃导致 DXSize var 未正确对齐。

但这只有在 32 位模式下编译。在 64 位模式下工作正常...

有什么线索吗?我错过了一些明显的东西吗?

4

1 回答 1

4

The align declspec only guarantees that the __m128i is aligned relative to the start of the data structure. If your memory allocator creates objects that aren't 16-byte aligned in the first place, the __m128i will be carefully misaligned. Many modern memory allocators give only 8-byte alignment.

You'll need to overload operator new for DXPoint to use an allocator with better alignment control, or use statically allocated and correctly aligned __m128is, or find some other solution.

--

Sorry, overlooked the "C++ beginner" part of your question. operator new overloading and custom memory allocators aren't really C++ beginner topics. If your application is such that you can allocate your DXPoint/DXSize objects statically (i.e. as globals instead of with 'new'), then that might also work. Otherwise you're diving in the pool at the deep end.

于 2010-07-10T19:55:34.357 回答