我正在写一个矩阵类:
template <typename T>
struct TMatrix44{
TMatrix44(){
// default construct an identity matrix
memcpy(m, TMatrix44<T>::TheIdentity().m, sizeof(TMatrix44<T>));
}
TMatrix44(
const T& m00, const T& m01, const T& m02, const T& m03,
const T& m10, const T& m11, const T& m12, const T& m13,
const T& m20, const T& m21, const T& m22, const T& m23,
const T& m30, const T& m31, const T& m32, const T& m33)
: _00(m00), _01(m01), _02(m02), _03(m03),
_10(m10), _11(m11), _12(m12), _13(m13),
_20(m20), _21(m21), _22(m22), _23(m23),
_30(m30), _31(m31), _32(m32), _33(m33)
{
}
static const TMatrix44<T>& TheIdentity()
{
static TMatrix44<T> sm(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
return sm;
}
// non-standard extension: nameless union and struct
union{
T m[4][4];
struct{
T _00, _01, _02, _03,
_10, _11, _12, _13,
_20, _21, _22, _23,
_30, _31, _32, _33;
};
};
// other contents...
};
当我使用此模板时:
TMatrix44<float> m;
我发现m的内容不是单位矩阵,而是全部为零,当我调试代码时,我发现该错误是在TheIdentity静态方法中:
static const TMatrix44<T>& TheIdentity()
{
static TMatrix44<T> sm(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
return sm; // sm here is still zero matrix, I have no idea what happened!!!
}
为什么sm不是用身份构建的?太奇怪了!