Reputation: 1755
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;
}
}
}
and
void foo(Eigen::MatrixXd* container){
for(i=0;i<container->rows();i++){
for(j=0;j<container->cols();j++){
container->coeffRef(i,j)=47;
}
}
}
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?
Upvotes: 2
Views: 6875
Reputation: 13536
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.
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.
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.
Upvotes: 5
Reputation: 1592
With C++ code, there is the expectation that if a parameter is passed as pointer rather than reference, then the null pointer is a valid argument.
That is, by default you should use reference parameters. Only use pointers if the parameter is in some way "optional" and you want the caller to be able to pass the null pointer to signify "no value".
Upvotes: 3
Reputation: 27252
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.
Upvotes: 0