首先 - 对细节感到抱歉。我通常会尝试将我的 SO 问题归结为仅包含相关内容的通用“A 类”内容,但我不确定这里问题的根源是什么。
我有一个看起来像这样的矩阵类模板(仅显示我认为的相关部分):
template <std::size_t R, std::size_t C>
class Matrix
{
private:
//const int rows, cols;
std::array<std::array<float,C>,R> m;
public:
inline std::array<float,C>& operator[](const int i)
{
return m[i];
}
const std::array<float,C> operator[](const int i) const
{
return m[i];
}
template<std::size_t N>
Matrix<R,N> operator *(const Matrix<C,N> a) const
{
Matrix<R,N> result = Matrix<R,N>();
// irrelevant calculation
return result;
}
// ... other very similar stuff, I'm not sure that it's relevant
}
template <std::size_t S>
Matrix<S,S> identity()
{
Matrix<S,S> matrix = Matrix<S,S>();
for(std::size_t x = 0; x < S; x++)
{
for(std::size_t y = 0; y < S; y++)
{
if (x == y)
{
matrix[x][y] = 1.f;
}
}
}
return matrix;
}
我对整个班级进行了单元测试,乘法和身份工厂似乎都工作正常。但是,然后我在这个方法中使用它,它被调用了很多次(我认为如果你曾经写过一个渲染器,很明显我在这里想要做什么):
Vec3i Renderer::world_to_screen_space(Vec3f v)
{
Matrix<4,1> vm = v2m(v);
Matrix<4,4> projection = identity<4>(); // If I change this to Matrix<4,4>(), the error doesn't happen
projection[3][2] = -1.f;
vm = projection * vm;
Vec3f r = m2v(vm);
return Vec3i(
(r.x + 1.) * (width / 2.),
(r.y + 1.) * (height / 2.),
r.z
);
}
经过一段时间和对该方法的一些随机调用后,我得到了这个:
Job 1, 'and ./bin/main' terminated by signal SIGBUS (Misaligned address error)
但是,如果我将行更改identity<4>()
为Matrix<4,4>()
错误不会发生。我是 C++ 新手,所以它一定很愚蠢。
那么,(1)这个错误是什么意思,(2)我是如何设法射中自己的腿的?
更新:当然,这个错误不会在 LLDB 调试器中重现。
更新 2:这是我通过 Valgrind 运行程序后得到的结果:
==66525== Invalid read of size 4
==66525== at 0x1000148D5: Renderer::draw_triangle(Vec3<float>, Vec3<float>, Vec3<float>, Vec2<int>, Vec2<int>, Vec2<int>, Model, float) (in ./bin/main)
并且draw_triangle
正是调用world_to_screen_space
和使用它的结果的方法。
更新 3:我发现了问题的根源,它与这段代码没有任何关系——而且它也很明显。现在真的不知道该怎么处理这个问题。