Re: [eigen] is returning Eigen::Ref objects legit?

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


On Mon, May 20, 2013 at 6:36 PM, 何震邦 <jdh8@xxxxxxxxxxxxxx> wrote:
> 在 2013 五月 20 週一 15:38:12,Sébastien Barthélémy 寫道:
>> Hello,
>>
>> I'm giving new Eigen::Refs a try and thought they might be a handy
>> type to return (by const ref), especially when the implementation
>> knows the matrix size at compile time but the caller does not.
>
> Yes, it's a wrapper of reference.

ok, got it, I should have returned the Ref object by value. It seems I
expect Eigen to be a bit too magical.

Thank you for your help!

PS: Fixed example attached.
#include <iostream>
#include <Eigen/Eigen>
#include <memory>

class Interface {
public:
  virtual size_t size() const = 0;

  virtual void compute() = 0;

  virtual Eigen::Ref<const Eigen::Matrix<float,  6, Eigen::Dynamic>, Eigen::Aligned>
  get() const = 0;

  virtual ~Interface() {};
};

class Implementation10 : public Interface {
public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  Implementation10() {};

  size_t size() const {
    return 10;
  }

  void compute() {
    m_ = m_.Identity();
  }
  Eigen::Ref<const Eigen::Matrix<float,  6, Eigen::Dynamic>, Eigen::Aligned>
  get() const {
    return m_; // warning: returning reference to temporary
  }

private:
    Eigen::Matrix<float, 6, 10> m_;
};

Interface* createInterface() {
  return new Implementation10();
}

int main()
{
  std::cout << "Hello, world" << std::endl;
  const std::auto_ptr<Interface> interface(createInterface());
  Eigen::Matrix<float, 3, Eigen::Dynamic> triple(3, interface->size());
  interface->compute();
  triple = 3 * interface->get().topRows(3);
  std::cout << triple;
  return 0;
}


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