Registered Member
|
The following code block compiles fine, but throws a std::bad_alloc
I am writing expression templates that use Eigen as an underlying mechanism, so I would need to be able to pass these expressions around, and sometimes cast them to a matrix, like you would normally do in Eigen::MatrixXd(A+B), which works. any insight much appreciated! |
Registered Member
|
On GCC 4.4, it runs without throwing exceptions, but valgrind reports invalid reads. I do not know how these cause bad_alloc exceptions on your machine, but I think I can explain the invalid reads. The CwiseBinaryOperator you construct in get_x has references to A and B. After get_x returns to main, A and B disappear, so CwiseBinaryOperator now contains dangling references. In main, the CwiseBinaryOperator is cast to a MatrixXd, so it follows the dangling references and performs invalid reads.
|
Registered Member
|
This case can indeed be solved by storing the temporaries and, for example, passing them as const ref to the function. However, the following more elaborate example still fails although afaik everything is stored somewhere.
include file
simple test
In the include file, if you use the commented out typedef instead, it works fine. |
Registered Member
|
I think the issue here is that when you call MatrixSummer::get(), it calls MatrixHolder::get() which returns a MatrixXd. This MatrixXd is a temporary; your definition of MatrixSummer::get() is equivalent (I think) to
I find expression templates in C++ quite hard to understand and use, but it does teach you a lot about C++. |
Registered Member
|
Thank you so much for this answer! I cross-posted this question on stackoverflow, if you want, you could post this answer and I'll mark it there as well.
http://stackoverflow.com/questions/2116 ... s-segfault In addition, could you expand a little on the cases where you feel this would fail? |
Registered users: Baidu [Spider], Bing [Bot], Google [Bot], Yahoo [Bot]