Re: [eigen] Ref<> Problem

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




On Thu, Dec 4, 2014 at 12:05 PM, Christoph Hertzberg <chtz@xxxxxxxxxxxxxxxxxxxxxxxx> wrote:
On 04.12.2014 10:41, Gabriel wrote:
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 :-)?

That works for some parts, but there are still some pitfalls:

int main() {
  Eigen::MatrixXd M = Eigen::MatrixXd::Identity(3,3);

  A A1(3*M);   // creates temporary in A1
  {
    A A2(2*M); // creates temporary in A2
    A1 = A2;   // temporary in A1 is not destructed! --> LEAK
  } // temporary in A2 gets destructed, invalid reference in A1!

  std::cout << A1.r << std::endl; // PROBLEM!
}

So generally, like C++ references, Ref should be considered as initialize-once variables. And, like in C++, strange things can happen, if the variable by which it got initialized runs out of scope before the reference does.

These pitfalls go away if the creation of a temporary is disabled in the Ref<> object (bug 884) which seems to be OK in Gabriel's use case.

gael 


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