2

如果 a 有一个将特征矩阵作为参数的函数,那么两者之间的区别是什么:

void foo(Eigen::MatrixXd& container){
    for(i=0;i<container.rows();i++){
        for(j=0;j<container.cols();j++){
            container(i,j)=47;
        }
    }
}

void foo(Eigen::MatrixXd* container){
    for(i=0;i<container->rows();i++){
        for(j=0;j<container->cols();j++){
            container->coeffRef(i,j)=47;
        }
    }
}

Eigen 文档中,他们只介绍了第一种方法——这是否意味着这种方法有任何优势?const在第一种情况下传递 Matrix 引用时不使用的缺点是什么?

4

3 回答 3

5

引用很好,因为没有空引用之类的东西,所以使用引用参数可以降低有人用无效值调用你的函数的风险。

另一方面,一些编码标准建议使用您打算修改指针而不是非常量引用的参数。这迫使调用者显式地获取他们传入的任何值的地址,从而使值将被修改更明显。指针与非常量引用的选择取决于您。

但是,如果您不打算修改参数,那么将其设为 const 引用绝对是可行的方法。它避免了传递无效指针的问题,允许您传入临时变量,并且调用者不关心参数是否通过引用获取,因为它不会被修改。

于 2013-06-10T18:41:10.363 回答
3

对于 C++ 代码,期望如果参数作为指针而不是引用传递,则空指针是有效参数。

也就是说,默认情况下您应该使用引用参数。仅当参数以某种方式“可选”并且您希望调用者能够传递空指针以表示“无值”时才使用指针。

于 2013-06-10T18:39:55.353 回答
0

see the line:

container(i,j)=47.

That's not a constant operation, so you're not going to be able to set it to const.

One way a reference is different than a pointer is that your container reference can't be null. Pass by reference is a good way to avoid some errors while getting the benefits of not copying.

于 2013-06-10T18:30:00.410 回答