How to initialize a link to an object if the link is a member of a class?

Let's say the class contains a link called matrix _:

Class.h

class Class
{
Matrix& matrix_;
}

Class.cpp

Class::Class() : matrix_(Matrix())
{
}

I get an error: invalid initialization of a non-constant reference of type "Matrix & from temporary type" Matrix ".

I see that the problem is that the temporary object will disappear and the link will point to NULL. How to create a permanent object for a link? I want to use the link because this member must be permanent.

+3
source share
4 answers

Class::Class() : matrix_(Matrix()) trying to establish a link to an indication of a temporary object that is illegal.

, const , , .

, :

class Class
{
const Matrix matrix_;
};

:

Class::Class() : matrix_() /* or any params to the constructor if you need them */
{
}
+5

​​ .

class Class
{
  Matrix & matrix_;
public:
  Class(Matrix & matrix);
};

Class::Class(Matrix & matrix) : matrix_(matrix)
{
}

, ( ++ ), , const.

+3

, . "" . ( ) . , , , .

, :

Class.h

class Class
{
Matrix* const matrix_;
}

Class.cpp

Class::Class() : matrix_(new Matrix())
{
}
+1
source

You do not need to use the link in order for this member to be permanent. You can use boost::scoped_ptr<const Matrix>.

class Class
{
public:
    Class();
private:
    boost::scoped_ptr<const Matrix> _matrix;
}

Class::Class() : _matrix(new Matrix)
{
}
+1
source

Source: https://habr.com/ru/post/1775000/


All Articles