指针和传递特征对象作为参数时的参考差异 [英] Pointer vs Reference difference when passing Eigen objects as arguments

查看:253
本文介绍了指针和传递特征对象作为参数时的参考差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果a有一个以特征矩阵作为参数的函数,则会有以下区别:

If a have a function that takes a Eigen matrix as an argument, what would be the difference between:

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文档,他们只提出第一种方法 - 这是否意味着这种方法有什么优点?在第一种情况下传递Matrix引用时,不使用 const 有什么缺点?

In Eigen documentation, they only present the first method - does that mean that there are any advantages to that approach? And what are the drawbacks of not using const when passing the Matrix reference in the first case?

推荐答案

引用很好,因为没有空引用,所以使用引用参数可以减少某人使用无效值调用函数的风险。

References are nice because there is no such thing as a null reference, so using a reference parameter reduces the risk of someone calling your function with an invalid value.

另一方面,一些编码标准推荐做参数,你打算修改指针,而不是非const引用。这迫使调用者显式地获取他们传递的任何值的地址,使得值将被修改更明显。

On the other hand some coding standards recommend making parameters you intend to modify pointers instead of non-const references. This forces the caller to explicitly take the address of any value they pass in making it more obvious the value will be modified. The choice of pointer vs. non-const reference is up to you.

但是,如果你不打算修改参数,那么使它成为const引用是绝对的方式去。它避免了传递无效指针的问题,允许你临时传递,而调用者不关心参数是否被引用,因为它不会被修改。

However, if you do not intend to modify the parameter then making it a const reference is definitely the way to go. It avoids the problem of passing invalid pointers, allows you to pass in temporaries, and the caller doesn't care if the parameter is taken by reference since it isn't going to be modified.

这篇关于指针和传递特征对象作为参数时的参考差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆