Reputation: 7349
I expected that when I create an Eigen matrix and set it equal to another matrix, that I would see reference semantics. Specifically, I expected the output of this
#include <iostream>
#include "Eigen/Dense"
using Eigen::MatrixXd;
using Eigen::VectorXd;
int main() {
MatrixXd A = MatrixXd::Identity(1, 2);
MatrixXd B = A;
A(0, 0) = 4;
std::cout << "A: " << A << std::endl;
std::cout << "B: " << B << std::endl;
return 0;
}
to be
A: 4 0
B: 4 0
but I actually get
A: 4 0
B: 1 0
So I guess Eigen is using copy semantics for these constructors. But if I explicitly reference the input (like in a class constructor), I still seem to be getting copy semantics. Specifically, the output of
#include <iostream>
#include "Eigen/Dense"
using Eigen::MatrixXd;
using Eigen::VectorXd;
class Holder {
public:
MatrixXd mat;
Holder(MatrixXd &A) : mat(A) {
}
};
int main() {
MatrixXd A = MatrixXd::Identity(1, 2);
Holder C(A);
A(0, 0) = 4;
std::cout << "A: " << A << std::endl;
std::cout << "C: " << C.mat << std::endl;
return 0;
}
is
A: 4 0
C: 1 0
So the question is... why does it seem like Eigen is copying the matrices instead of referencing them?
Also, in the end I would like to define a single matrix (e.g. A
in the above example), then create many instances of the Holder
class, where each instance has a reference to the same matrix. Specifically, I want the behavior that modifying A
modifies the matrices in the Holder
classes. The catch is that I cannot modify the Holder
class itself. So, for instance, I could not change the Holder
class to save a pointer to A
instead of A
itself. How would I accomplish that?
I have scoured the Eigen docs, but can't seem to find the explanation.
Upvotes: 0
Views: 694
Reputation: 1544
Eigen is copying because you are asking it to copy. If you want to have a reference to a Matrix, you have to specify it using the correct syntax. In C++, reference variables are specified with the &
character:
MatrixXd A = MatrixXd::Identity(1, 2); // this is an object
MatrixXd& B = A; // this is a reference to an object (notice the &)
Upvotes: 1