warning C4316: object allocated on the heap may not be aligned 16

后端 未结 4 716
面向向阳花
面向向阳花 2020-12-30 01:16

Important Information:

  • Development OS: Windows 8.1 64 bit
  • Target OS: Windows 8.1 64 bit
  • IDE: Visual Studio 2013 Professional
相关标签:
4条回答
  • 2020-12-30 01:55

    If you look at the pre-processed code you'll probably find something like this __declspec(align(16)) in there, requesting to be aligned at 16 bytes while new may not align at that constraint. Accoding to http://msdn.microsoft.com/en-us/library/vstudio/dn448573.aspx you can fix it by Override operator new and operator delete for over-aligned types so that they use the aligned allocation routines—for example, _aligned_malloc and _aligned_free.

    0 讨论(0)
  • 2020-12-30 01:55

    DirectX::XMMATRIX contains SSE data (and is marked with __declspec(align(16)) because of this), and therefore needs to be aligned on 16B boundary, otherwise instructions accessing it will cause access violation.

    The warning tells you there is no guarantee memory returned by operator new is 16B aligned.

    Can you create the object as a global or local variable instead? That way the compiler can enforce the alignment. If you cannot, you can provide overloaded new and delete for your Direct3D class implemented using _aligned_malloc and _aligned_free.

    0 讨论(0)
  • 2020-12-30 01:58

    You need to override the new and delete operators, like this:

    __declspec(align(16)) class MyClass
    {
        public:
        DirectX::XMMATRIX           m_projectionMatrix;
    
        virtual ~MyClass()
        {
        }
    
        void* operator new(size_t i)
        {
            return _mm_malloc(i,16);
        }
    
        void operator delete(void* p)
        {
            _mm_free(p);
        }
    };
    
    0 讨论(0)
  • 2020-12-30 02:11

    What does C4316 mean?

    C4316 is the error code. It's a unique identifier that makes it easy to find the documentation.

    What is causing it in my code?

    The usage of the DirectX::XMMATRIX class. Instances of that class must be aligned on 16-byte boundaries. The compiler makes sure that whenever you create a JGLib::Graphics::Direct3D instance on the stack or at global scope, it will align it properly, but if you allocate an instance dynamically on the heap, the compiler can't guarantee that the object will be aligned properly, because malloc() and friends typically only guarantee 8-byte alignment.

    What implications could this have in the future, if I ignore it?

    Your code may crash when accessing those matrix instances due to SSE instructions operating on misaligned data.

    How do I "fix" the problem that is causing this warning to appear?

    As the documentation suggests, you need to override your class's operator new and operator delete in order to guarantee 16-byte alignment. You can use _aligned_malloc() and _aligned_free() to allocate and free memory aligned on larger alignments.

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