Having Ref object as class member

3926 views c++

I wish to pass by reference my data to a class where the reference itself should be the public variable, to be accessed by member functions. If I declare my class and its constructor

class max_likelihood { 
MatrixXd dat
max_likelihood(const Ref<const MatrixXd>& dat_in)
{dat = dat_in;}

I get functioning code but end up creating a copy of dat, which I would like to avoid.

I have tried to do instead:

class max_likelihood {
const Ref<const MatrixXd>& dat;
max_likelihood(const Ref<const MatrixXd>& dat){}

But this does not work and/or won't let me access the reference to dat and does not even compile.

Based on my research I have found this bit from this question

if you want to reassign a Ref to reference another buffer, then use a placement new to re-call the constructor of Ref. Don't forget to call the destructor first.

I believe this may help answer my question but I do not know what these instructions would mean in practice, hence my question here. Specifically, I suppose I am creating a new instance of a Ref object to pass around the passed reference. Can someone help me interpret the answer to this or perhaps suggest a more elegant way to use Ref objects within classes when the source data is created elsewhere, say read in from a file via main?

Any help would be much appreciated.

answered question

Have you considered changing max_likelihood to take your argument by value or adding an overload that takes it's argument by rvalue reference? You could avoid the copy in cases where it isn't needed.

Using placement new won't save you a copy. The linked question is a move in the wrong direction.

Please share a Minimal, Complete, and Verifiable example to better illustrate the use case.

Do not overcomplicate the matter, use move semantics

2 Answers


You can use the initializer list:

struct max_likelihood { 
    MatrixXd& dat
    max_likelihood(MatrixXd& dat_in) : dat(dat_in) {}

posted this

The member variable dat is a const reference that needs to be initialized.

max_likelihood(const Ref<const MatrixXd>& argdat):dat(argdat){}

posted this

Have an answer?


Please login first before posting an answer.