代码之家  ›  专栏  ›  技术社区  ›  shanksk

通过参考传递的特征参数

  •  0
  • shanksk  · 技术社区  · 6 年前

    我正在关注本征文档中的这一页,试图了解本征参数的使用

    https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html

    以下代码按预期工作

    #include <iostream>
    #include <Eigen/Dense>
    
    // a - nonwriteable, b - writeable
    void eigen_reference_class(
        const Eigen::Ref<const Eigen::Array<double, 
        Eigen::Dynamic, 3> >& a, Eigen::Ref<Eigen::Array<double, Eigen::Dynamic, 3> > b) {
        b = 2 * a;
    }
    
    void eigen_reference(const Eigen::Array<double, 1, 3>& a, Eigen::Array<double, 1, 3>& b) {
        b = 2*a;
    }
    
    template<typename Derived> 
    void eigen_template(const Eigen::PlainObjectBase<Derived>& a, Eigen::PlainObjectBase<Derived>& b) {
        b = 2*a;
    }
    
    int main()
    {
        Eigen::Array<double, 1, 3> a, b, c, d;
        a << 1, 2, 3;
        eigen_reference_class(a, b);
        eigen_reference(a, c);
        eigen_template(a,  d);
        std::cout << "a : \n" << a << std::endl;
        std::cout << "b: \n" << b << std::endl;
        std::cout << "c: \n" << c << std::endl;
        std::cout << "d: \n" << d << std::endl;
    
    }
    

    但是,如果数组的初始声明更改为

    Eigen::Array<double, Eigen::Dynamic, 3> a, b, c, d;
    

    然后程序将无法编译,并出现以下情况:

    error: invalid initialization of non-const reference of type ‘Eigen::Array<double, 1, 3>&’ from an rvalue of type ‘Eigen::Array<double, 1, 3>’       
         eigen_reference(a, c);
    

    或将因分段错误而失败,即使 a 保留。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Henri Menke    6 年前

    我喜欢看什么 int 在这种情况下确实如此,因为它可以帮助我更容易地理解这种情况下发生的更复杂的事情。

    想象你有一个 struct 持有 内景 可隐式转换为 内景 ,以便您可以使用它代替 内景 ,例如:

    struct Integer {
        int m_int;
        operator int() { return m_int; }
    };
    

    现在定义两个函数,一个取 int const & 还有一个拿着 int &

    void const_ref(int const &) {}
    void ref(int &) {}
    

    如果我们在这些函数中使用正则整数,就不会有什么意外了。

    int j = 3;
    const_ref(j);
    ref(j);
    

    但如果我们使用 Integer 相反,它不再编译。

    Integer i{2};
    const_ref(i);
    ref(i);
    

    错误如下

    error: no matching function for call to 'ref'
        ref(i);
        ^~~
    note: candidate function not viable: no known conversion from 'Integer' to 'int &' for 1st argument
    void ref(int &) {}
         ^
    1 error generated.
    

    现在的问题是,为什么 const_ref 工作,但 ref 不会吧?

    在呼叫中 const\u参考号 将运算符转换为 内景 调用,它返回一个临时 内景 我们可以绑定一个常量引用。我们无法将可变引用绑定到此临时对象,因为这将导致奇怪的效果。假设函数 参考 修改参数,但在这种情况下,它将修改临时参数,并且不会向原始参数写入任何内容 整数 你传入的。。。一个有保证的bug。


    在您的代码中是相同的。 Eigen::Array<double, Eigen::Dynamic, 3> 可以隐式转换为 Eigen::Array<double, 1, 3> 但不能将可变引用绑定到临时引用。