You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Eigen::Ref执行矩阵乘法时调用拷贝构造函数异常问题

Eigen Ref类使用时出现意外拷贝/内存分配问题

我编写了如下代码:

#include <Eigen/Eigen>
#include <iostream>

int main(int argc, char **argv) {
    std::cout << EIGEN_WORLD_VERSION << "." << EIGEN_MAJOR_VERSION << "." << EIGEN_MINOR_VERSION << std::endl;

    Eigen::Vector4f vector{
            0.0f,
            0.0f,
            1.0f,
            0.0f
    };

    const Eigen::Matrix4f M = Eigen::Matrix4f().setOnes();
    Eigen::Vector4f out_vec;
    const Eigen::Ref<const Eigen::MatrixXf> M_ref(M);
    out_vec = M * vector;
    out_vec = M_ref * vector;
    return 0;
}

执行M_ref * vector时,会触发矩阵拷贝构造函数并分配内存(在__libc_malloc断点处可捕获),这与Ref类预期的零拷贝引用行为不符。

若将const Eigen::Ref<const Eigen::MatrixXf> M_ref(M);替换为固定尺寸的const Eigen::Ref<const Eigen::Matrix4f> M_ref(M);,则无内存分配,但仍会调用拷贝构造函数。

当前使用环境:Eigen版本3.4.0、GCC 11.4.0,编译选项为-std=gnu++17。请问是否有人遇到过该问题?

内容的提问来源于stack exchange,提问作者Long Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 19:47:03