Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

c++ - Crash after m = XMMatrixIdentity() - alignment memory in classes?

I was looking at the tutorials in DirectX SDK. Tutorial 5 works fine, but after I have copied and separated the code to my own classes, I got strange error during launching my application.

The line is:

g_World1 = XMMatrixIdentity();

Because of it, I got error in xnamathmatrix.int operator= which looks like that:

XMFINLINE _XMMATRIX& _XMMATRIX::operator=
(
    CONST _XMMATRIX& M
)
{
    r[0] = M.r[0];
    r[1] = M.r[1];
    r[2] = M.r[2];
    r[3] = M.r[3];
    return *this;
}

And the error message is:

Access violation reading location 0xffffffff

I have read somewhere that it could be caused by something connected to XMFLOAT4X4 / XMMATRIX:

Have you considered using XMFLOAT4X4 to store the matrix, and only using XMMATRIX?

But I think I already use XMMATRIX.

MyClass.h:

private:
    XMMATRIX g_World1;

MyClass.cpp:

void init(){
   g_World1 = XMMatrixIdentity();
}

I don't think I should change XMMATRIX g_World1; to XMFLOAT4X4 g_World1, because it produces errors like:

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'XMMATRIX' (or there is no acceptable conversion)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since XMMATRIX represents a 16-byte aligned 4x4 matrix, the unaligned allocation of g_World1 causes the access violation (simply put, g_World1's address is not divisible by 16).

Sort of solution: enable structure member alignment by 16 bytes (for MyClass to have the g_World1 "in place"). But still you'll have to ensure, that MyClass instances reside at the addresses divisible by 16.

You can use the placement 'new' operator to allocate MyClass objects.

About alignment see here: How to align pointer


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...