Registered Member
|
I'm a little befuddled why 1) this compiles or 2) this runs so slowly:
If you replace
with
then it no longer compiles. I'm guessing that what's happening is that the compiler sees the type mismatch above but also sees that the reference will be const and that there's a copy constructor that will convert Eigen::Matrix<double,Eigen::Dynamic,3> to Eigen::MatrixXd. It's a bit disappointing because this discourages good programming habits like creating short names to const references. Of course one can say, "Just always use the right type" but there's no warning here and it's an easy trap to fall into with some many template parameters. |
Moderator
|
You found the correct answer by yourself. Forbidding such conversions would be unexpected for a lot of other users as this would lead to situations like:
won't trigger a copy, but you will loose the compile-time knowledge that no_cpy has only 3 columns. |
Registered Member
|
Thanks for the quick response. So, do I understand correctly that the problem is, in order to allow copy conversions of plain objects (non references, non pointers) in C++ one _must_ also allow this "copy during assignment to const reference" behavior?
The thing that confuses me a little is that it _only_ happens if the reference is const. Is there no way to override the copy to "const ref" operator? |
Moderator
|
You are right. And we cannot distinguish between a copy conversions of plain objects versus a copy to a const reference because what happens when doing:
Matrix3f a; const MatrixXd &A = a; is that the C++ compiler create a temporary MatrixXd object from a: MatrixXd tmp(a); and then this temporary is bound to the const reference: const MatrixXd &A = tmp; This does not work with non const references because in C++, only const references can be bound to temporaries. |
Registered users: Bing [Bot], Google [Bot], Yahoo [Bot]