【发布时间】:2019-04-14 10:08:36
【问题描述】:
我通过编写以下代码来测试变量是否被复制。这段代码来自官方文档:https://eigen.tuxfamily.org/dox/classEigen_1_1Ref.html
void cov(const Ref<const MatrixXf> & x, const Ref<const MatrixXf> & y, Ref<MatrixXf> C)
{
cout << "address of x : " << &x << endl;
cout << "address of C : " << &C << endl;
}
int main(int argc, const char * argv[]) {
MatrixXf m1(3,3);
MatrixXf m2(3,3);
MatrixXf m3(3,3);
m1 << 1,2,3,4,5,6,7,8,9;
m2 << 1,2,3,4,5,6,7,8,9;
m3 << 1,2,3,4,5,6,7,8,9;
cout << "address of m1 : " << &m1 << endl;
cout << "address of m3 : " << &m3 << endl;
cov(m1, m2, m3);
}
输出如下。
address of m1 : 0x7ffeefbff4e8
address of m3 : 0x7ffeefbff498
address of x : 0x7ffeefbff370
address of C : 0x7ffeefbff308
x 和 m1、m3 和 C 的地址不同(我认为它们应该是相同的,因为我通过引用传递变量)。谁能给我解释一下为什么?
感谢@Nelfeal 的回答。我尝试使用调试器来证明这一点。 以下是上述代码的调试信息。我们可以在 m1 和 x 中看到这一点。 “m_data”共享相同的地址 0x329f800。
但是,有人可以告诉我以下两段代码的区别吗?我想“Ref”本身已经是一个引用,那为什么还要加上引用标记“&”呢?
void cov(const Ref<const MatrixXf> x, const Ref<const MatrixXf> y, Ref<MatrixXf> C)
void cov(const Ref<const MatrixXf> &x, const Ref<const MatrixXf> &y, Ref<MatrixXf> C)
【问题讨论】: