Eigen has introduced the Ref<> class to write functions with Eigen objects as parameters without the use unnecessary temporaries, when writing template functions is not wanted. One can read about this here.
When searching the internet further, I found several different declarations of parameters using the Ref<> class. In the Eigen documentation they use const Eigen::Ref<const Eigen::MatrixXf>&
for a read-only parameter in the first example. In the second example Eigen::Ref<Eigen::MatrixXd>
is introduced for read-and-write parameters, BUT here const Eigen::Ref<const Eigen::MatrixXd>
is used for read-only parameters (no reference). So my question is:
What is the difference between the following declarations and when do I use which?`
const Eigen::Ref<const Eigen::MatrixXd>&
const Eigen::Ref<const Eigen::MatrixXd>
const Eigen::Ref<Eigen::MatrixXd>&
const Eigen::Ref<Eigen::MatrixXd>
Eigen::Ref<const Eigen::MatrixXd>&
Eigen::Ref<const Eigen::MatrixXd>
Eigen::Ref<Eigen::MatrixXd>&
Eigen::Ref<Eigen::MatrixXd>
For completeness I listed every possible combination of const usage and the reference.
In general, using a non const reference like Ref<T>&
is never a good idea because this will only work if the caller already has a Ref<T>
object at hand. This discards 5 and 7.
The cases 3 and 4 does not make sense, and they won't compile in general.
Then, there is not much difference between a const Ref<const T>
and a const Ref<const T>&
because it is unlikely that the function is called with an existing Ref<const T>
object, and so a Ref<const T>
will have to be created in most cases anyway. Nevertheless, we could still recommend 1 over 2 or 6.
So in summary, we could recommend Ref<T>
for a writable reference, and const Ref<const T>&
for a const reference.
The option 6, Ref<const T>
, might still be interesting if you want to change the matrix that is referenced (not its content) through a call to Ref
constructor using placement new.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With