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/

相关文章:

python - python中的线程: retrieve return value when using target=

c++ - 当我的代码被 GCC 编译时内存泄漏

matlab - 如何找到矩阵中重复的值及其所属的行?

matlab - 在matlab中合并两个矩阵

performance - Matlab bsxfun() - 如何解释沿不同维度扩展时的性能差异?

c - 可以在事务期间检查 WAL 文件吗?

c++ - Windows 任务管理器显示进程虚拟内存的哪一部分

c++ - gcc 4.8 或更早版本是否存在关于正则表达式的问题?

c++ - 动态推断函数的返回类型

c++ - C++ 中的 Const 函数和接口(interface)