Re: [eigen] Ref<> Problem |
[ Thread Index |
Date Index
| More lists.tuxfamily.org/eigen Archives
]
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.
Analogous example with C++ references:
struct B{
const double& r;
B(const double& r_) : r(r_) {}
};
B foo() {
double x = 3.0;
return B(x);
// referenced x value will be invalid as soon as foo() exits
}
int main() {
double y = 1.0;
B b1(2*y); // temporary created during construction but gets
// out of scope before b is usable
B b2 = foo(); // x in foo() is out of scope now
std::cout << b1.r << "\n" << b2.r << std::endl;
}
Christoph
--
----------------------------------------------
Dipl.-Inf., Dipl.-Math. Christoph Hertzberg
Cartesium 0.049
Universität Bremen
Enrique-Schmidt-Straße 5
28359 Bremen
Tel: +49 (421) 218-64252
----------------------------------------------