This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Initializing a reference member with block

Tags: None
(comma "," separated)
MarkusJ
Registered Member
Posts
2
Karma
0
Hi,

if I run the following code:

Code: Select all
#include <Eigen/Dense>
#include <iostream>

using namespace Eigen;
using namespace std;

class Test
{
public:
  Test( const MatrixXd& _X ) : X(_X)
  {
    cout << X << "\n\n";
  }
  void print()
  {
    cout << X << "\n\n";
  }

private:
  const MatrixXd& X;
};

int main( void )
{
  MatrixXd A(4,2);
  A << 1, 2, 3, 4, 5, 6, 7, 8;

  Test t(A);
  t.print();
 
  Test t2( A.bottomRows(2) );
  t2.print();
}


I get the following result:

Code: Select all
1 2
3 4
5 6
7 8

1 2
3 4
5 6
7 8

5 6
7 8

4.94066e-324 6
4.94066e-324 8


What is my mistake?

Thanks a lot,
Markus
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
your mistake is that first, A.bottomRows(2) returns a Block<MatrixXd> that is then converted to a temporary MatrixXd object when you call the ctor of Test. Then you store a reference to this temporary which is by definition destroyed right after the end of the ctor, making your reference invalid.
MarkusJ
Registered Member
Posts
2
Karma
0
Thank a lot - please excuse my ignorance.

What would be the most elegant solution to let a class have access to a block
of a matrix that is altered outside during its lifetime?

Cheers,
Markus
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
you can store a Block<MatrixXd> object by value.


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], Yahoo [Bot]