这个问题可能很愚蠢,但我是初学者。 当我像这样在本地范围内创建 Eigen::MatrixXd 时:
void foo(){
Eigen::MatrixXd m(rows,cols);
// do stuff
}
对象会在堆上还是栈上? 我希望它在堆栈上,因为我没有使用“new”关键字。
最佳答案
Eigen::Matrix
的特化实例既可以存储在堆上也可以存储在栈上
如 the accepted answer 中所述, m
具有自动存储期限。然而,重要的是要指出,随后的声明
Of course
Eigen::MatrixXd
will manage much of its internal memory dynamically, but you do not need to concern yourself with that.
通常不适用于 Eigen::Matrix
的特化实例,并且还必须指出,这确实是您可能需要关心的事情,尤其是在不允许动态内存的环境中工作时(例如,嵌入式环境)。
动态大小Eigen
矩阵
您正在使用动态大小的矩阵(强调 X
中的 Eigen::MatrixXd
。任何 Eigen::MatrixX...
类型只是 Eigen::Matrix< ..., Dynamic , Dynamic >
的类型定义,其中 Dynamic
表示它的大小在编译时是未知的:
const int Eigen::Dynamic
This value means that a positive quantity (e.g., a size) is not known at compile-time, and that instead the value is stored in some runtime variable.
Eigen::Matrix
的 Eigen 文档,所有Eigen::MatrixX...
是专门化的,明确了动态大小矩阵的数据将存储在堆上[强调我的]:
Fixed-size versus dynamic-size:
Fixed-size means that the numbers of rows and columns are known are compile-time. In this case, Eigen allocates the array of coefficients as a fixed-size array, as a class member. ...
Dynamic-size means that the numbers of rows or columns are not necessarily known at compile-time. In this case they are runtime variables, and the array of coefficients is allocated dynamically on the heap.
固定尺寸 Eigen
矩阵
然而,从上面引用的第一段可以清楚地看出,如果 m
应该是固定大小的 Eigen::Matrix
特化,它的数据将(因为它具有自动存储持续时间)存储在堆上。这是重要的保证。对于不允许动态内存分配的项目(例如嵌入式)。
事实上,Eigen 甚至提供了一个内部预处理器指令,EIGEN_RUNTIME_NO_MALLOC
,可用于禁止 Eigen 模块内的任何动态内存分配。
These macros are mainly meant for people developing Eigen and for testing purposes. Even though, they might be useful for power users and the curious for debugging and testing purpose, they should not be used by real-word code.
EIGEN_RUNTIME_NO_MALLOC
- if defined, a new switch is introduced which can be turned on and off by callingset_is_malloc_allowed(bool)
. Ifmalloc
is not allowed and Eigen tries to allocate memory dynamically anyway, an assertion failure results. Not defined by default.
然而,强调“不应由真实代码使用”,但 Eigen 的用户可以将其用于测试目的。
固定大小的矩阵可能仍会在堆上结束!
正如@superjax 在评论中提到的:
One last thing I would add is that fixed-size matrices exceeding the EIGEN_STACK_ALLOCATION_LIMIT will also be allocated on the heap. (The default is 128kb, but that can be changed)
关于c++ - 是在堆上自动创建的特征矩阵吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55966046/