Using XMVECTOR from DirectXMath as a class member causes a crash only in Release Mode?

后端 未结 1 1840
北海茫月
北海茫月 2021-01-15 11:44

I\'ve been trying to use XMVECTOR as a class member for a bounding box, since I do a lot of calculations, but I use the XMFLOAT3 only once per frame, so the bounding box has

相关标签:
1条回答
  • 2021-01-15 12:03

    The class is not being created at an aligned address, so even though the XM* members are aligned on 16-byte boundaries, the parent's alignment miss-aligns them, causing the crash.

    To prevent this you need to use _mm_alloc (which really just wraps _aligned_alloc), or replace the default allocator with one that returns blocks minimally aligned to 16 bytes (under x64 this the case with the default allocator).

    a simple solution to this in C++ is to create a base class for all classes the contain XM* members that looks like the following:

    template<size_t Alignment> class AlignedAllocationPolicy
    {
        public:
        static void* operator new(size_t size)
        {
            return _aligned_malloc(size,Alienment);
        }
    
        static void operator delete(void* memory)
        {
            _aligned_free(memory);
        }
    };
    
    class MyAlignedObject : public AlignedAllocationPolicy<16>
    {
    //...
    };
    

    As pointed out by @Dave, this is a minimal example, you'd want to overload all the new and delete operators, specifically new[] and delete[]

    0 讨论(0)
提交回复
热议问题