Re: [eigen] Ref<> Problem

[ Thread Index | Date Index | More lists.tuxfamily.org/eigen Archives ]



I give it a  try:

struct A{
        // constructor does not generate a temporary:
        template<class Derived>
        A(const Eigen::MatrixBase<Derived> & in) : r(in) {}
        // initializing r might create a temporary but that is stored in r


        A  & operator=(const A & other)
        {
            new (&r) Eigen::Ref<const Eigen::MatrixXd>(other.r);

            return *this;
        }

        Eigen::Ref<const Eigen::MatrixXd> r;
    };


Is that correct, it seems to work :-)?

On 12/04/2014 10:18 AM, Gael Guennebaud wrote:
a1 = a2 won't compile because the Ref<> members are const references. To make it compile with the expected behavior (i.e., copy of the referenced data and not deeply copy the coefficients), you have to implement yourself the copy-assignment operator and call the ctor of Ref<> through the placement new syntax.

cheers,
gael 

On Thu, Dec 4, 2014 at 9:58 AM, Gabriel <gnuetzi@xxxxxxxxx> wrote:
Thanks a lot Christoph,

So what kind of strange things might happen:

So with your code, a temporary might be cosntructed by initializing r, but because it is generated in the classes scope it is bound to exist till struct A destructs?

If we assign elements of type A lets say
A a1;
A a2;
a1 = a2,
MIght be a problem , why?   a1 copied the reference, right? it is still valid , but if a2 internally stored a temporary than a1 refers to a temporary in a2 which might blow up somewhen ?

Is that the problem?


Thanks a lot!





On 12/04/2014 01:11 AM, Christoph Hertzberg wrote:
On 04.12.2014 00:14, Gabriel wrote:
How can I avoid such errors, and whats the correct way of storing a
reference to a Matrix  in a class?

You must avoid that a temporary is constructed which runs out of scope after being assigned to r:

  struct A{
    // constructor does not generate a temporary:
    template<class Derived>
    A(const Eigen::MatrixBase<Derived> & in) : r(in) {}
    // initializing r might create a temporary but that is stored in r

    Eigen::Ref<const Eigen::MatrixXd> r;
  };

Be aware that strange things might happen, when you try to copy-assign elements of type A.


Christoph








Mail converted by MHonArc 2.6.19+ http://listengine.tuxfamily.org/