Vio*_*ffe 2 c++ windows memory-alignment visual-c++
我有一节课:
class CMatrix4f
{
public:
CMatrix4f();
public:
__declspec(align(16)) float m[16];
};
Run Code Online (Sandbox Code Playgroud)
此类使用SSE实现矩阵操作,因此m 必须对齐才能使其工作.它大部分时间都可以工作,但有时我会在执行SSE指令时遇到段错误,例如_mm_load_ps因为m不是16字节对齐.到目前为止,我无法理解它发生在哪些情况.
当我这样做CMatrix4f * dynamicMatrix = new CMatrix4f();,是dynamicMatrix.m保证对齐?
如果我有课:
class MatrixWrapper {
public:
MatrixWrapper();
CMatrix4f _matrix;
};
Run Code Online (Sandbox Code Playgroud)
然后做:
MatrixWrapper * dynamicMatrixWrapper = new MatrixWrapper();
Run Code Online (Sandbox Code Playgroud)
为dynamicMatrixWrapper._matrix.m保证对齐?
我已经阅读了关于路由的MSDN文章,但目前还不清楚它是否适用于动态分配.
因为__declspec(align(#))是一个编译指令,MatrixWrapper使用new运算符创建对象可能会导致堆上的未对齐内存.您可以考虑使用 _aligned_malloc并动态分配内存,例如在构造函数中,然后_aligned_free在析构函数中使用它,通过混合静态和动态分配对象使事情变得更加困难.