To avoid useless and expensive copies, the internal solve_retval
structure stores the decomposition and right-hand-side by const references. However, the LDLT
object created in the Decomp::get
function is deleted at the same time this function returns, and thus the solve_retval
object references dead objects.
One possible workaround, is to add a Decomp::result_type
object in Solve
, and initialize it in Solve::get
. Moreover, to avoid multiple deep copies, I suggest to use const references for a few attributes as follow:
#include <Eigen/Dense>
#include <Eigen/Cholesky>
template <class EigenType> class Holder {
public:
typedef EigenType result_type;
private:
result_type in_;
public:
Holder(const EigenType& in) : in_(in) {}
const result_type& get() const { return in_; }
};
template <class Hold> class Decomp {
public:
typedef typename Eigen::LDLT
<typename Eigen::MatrixBase<typename Hold::result_type>::PlainObject>
result_type;
private:
const Hold& mat_;
mutable result_type result_;
mutable bool init_;
public:
Decomp(const Hold& mat) : mat_(mat), init_(false) {}
const result_type& get() const {
if(!init_) {
init_ = true;
result_.compute(mat_.get());
return result_;
}
}
};
template <class Derived, class OtherDerived> class Solve {
public:
typedef typename Eigen::internal::solve_retval
<typename Derived::result_type, typename OtherDerived::result_type>
result_type;
private:
const Derived& decomp_;
const OtherDerived& mat_;
public:
Solve(const Derived& decomp, const OtherDerived& mat)
: decomp_(decomp), mat_(mat) {}
result_type get() const {
return decomp_.get().solve(mat_.get());
}
};
The general rule is to store heavy objects by const reference (to avoid deep copies) and lightweight expressions by value (to reduce temporary life issues).