c++ - 是在堆上自动创建的特征矩阵吗?

标签 c++ matrix memory eigen

这个问题可能很愚蠢,但我是初学者。 当我像这样在本地范围内创建 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 calling set_is_malloc_allowed(bool). If malloc 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/

相关文章:

matlab - 3D 矩阵乘以 2D 矩阵

matlab - 如何从 MATLAB 中给定的输入数据生成以下矩阵和向量?

c++ - 重构使用 if 语句的重复范围检查

c++ - Visual Studio 2010 Express STL列表编译器错误

matrix - 在着色器中的二维图像矩阵上旋转 Z 轴

c++ - 宏是否分配内存?

objective-c - 为什么 NSColorPanel 交互会累积内存?

c++ - 如何在 QT 中对小部件进行逻辑分组以便于显示/隐藏?

c++ - 在 C++ 类中正确设计成员 setter/getter

linux - 给定程序使用/usr/bin/time 的内存使用情况