I used move semantics a la
class MyC {
public:
Eigen::MatrixXd f_bar_mat;
MyC::MyC(Eigen::MatrixXd f_bar_mat):f_bar_mat(std::move(f_bar_mat))
}
In the main
I have:
Eigen::MatrixXd f_bar_mat = Eigen::MatrixXd::Random(10000,200);
MyC MyInst(f_bar_mat);
MyC MyNewInst(MyInst.f_bar_mat); //transfer again
std::cout << "Access some element of the original matrix: " << f_bar_mat(3,2) << std::endl;
I realised only later that I erroneously called f_bar_mat
in the body of my main
after having transferred ownership.
However, the code still works; I don't get an error message.
Can someone help me understand the behaviour? My guess is that std::move
then simply resorts to a deep copy. Alternatively, should I be getting a segmentation fault error or will it reference something other than f_bar_mat
and create undefined behaviour?
CodePudding user response:
You are not moving main
's f_bar_mat
anywhere. Nowhere did you call std::move(f_bar_mat)
in main
.
You are moving only the parameter of the constructor which is also called f_bar_mat
but is not the same object as the one in main
(since it was not declared as a reference).
Since you are passing f_bar_mat
from main
as a lvalue to the constructor, the parameter object of the constructor will be copy-constructed from main
's f_bar_mat
. Only then you will move-construct the class member (also called f_bar_mat
) from the parameter object.
Similarly at // transfer again
you are not calling std::move
on MyInst.f_bar_mat
, so you are copy-constructing the constructor's parameter object again.