将矩阵对象作为MatrixBase引用传递给函数时会发生什么?我不知道幕后真的发生了什么.
一个示例功能代码是:
#include <Eigen/Core>
#include <iostream>
using namspace Eigen;
template <typename Derived>
void print_size(const MatrixBase<Derived>& b)
{
std::cout << "size (rows, cols): " << b.size() << " (" << b.rows()
<< ", " << b.cols() << ")" << std::endl;
std::cout << sizeof(b) << std::endl;
}
int main() {
Matrix<float, 2, 2> m;
m << 0.0, 0.1,
0.2, 0.3;
print_size(m);
std::cout << sizeof(m) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
它给出了以下输出:
size (rows, cols): 4 (2, 2)
1
16
Run Code Online (Sandbox Code Playgroud)
16对1差异来自哪里?
还有为什么转换是必要的呢?
提前致谢!
sizeof
在编译时进行评估,因此它与声明的(静态)对象类型有关.b
是类型MatrixBase<Derived>
(忽略引用,就像它一样sizeof
),它很可能是一个空基类,因此大小为1.
m
另一方面,它是一种类型Matrix<float, 2, 2>
,在你的平台上显然有16号.
我已经创建了一个演示此行为的实例sizeof
.