Q:

Strange bug with maxCoeff in Eigen

I have:
VectorXd my_vector;
MatrixXd my_matrix;

and dimensions are compatible in expressions bellow.
I remember reading in the Eigen doc that it is always better to evaluate expressions as a whole rather than evaluating smaller chuncks and then recombining results, because it gives Eigen more opportunities to optimize.
With that in mind, I would use:
// (1)
int index;
(my_vector.transpose() * my_matrix.leftCols(n_cols+1)).maxCoeff(&index);

rather than:
// (2)
int index;
RowVectorXd temp = my_vector.transpose() * my_matrix.leftCols(n_cols+1);
temp.maxCoeff(&index);

However (1) crashes when n_cols = 1 while using (2) instead of (1) exactly at the same place seems to always work. (Note that my_matrix has more than 1 columns...) 
QUESTIONS:
Why does (1) crash when (2) doesn't ???
How to prevent (1) from crashing while keeping it as a single expression? 
The error comes from Eigen's internal machinery assertions and it seems to me that it is because in (1) maxCoeff doesn't seem to realize that it is called on a row vector and not a general matrix - please correct me if I'm wrong. 

A:

As a workaround you can use .eval(). This effectively is the same as (2), just without the extra line of code:
(my_vector.transpose() * my_matrix.leftCols(n_cols + 1)).eval().maxCoeff(&index);

Regarding the internal workings of Eigen, when you call maxCoeff in case (1) the object that's being called on is (as you explicitly desired) a lazy evaluation construct (in this case GeneralProduct<Transpose<..>,Block<...> >) triggered by a call to mat.coeff(0,0) where mat is the GeneralProduct. Internally, the mat has (n_cols + 1) columns as opposed to 1 which is required by the row after the assertion (Matrix<Scalar,1,1> result = *this;)
This is what causes the evaluation, so we want to evaluate only the one element each time. Without the assert, trying to assign *this to result a resize is triggered causing the program to crash.
When using a temporary, the object is a Matrix<double,1,-1,1,1,-1> so coeff(i,j) just becomes a simple call to m_storage.data()[colId + rowId * m_storage.cols()].
All this becomes a moot point in Eigen 3.3 as the entire coeff(i,j) is now return m_evaluator.coeff(row, col);
TLDR
Upgrade to Eigen 3.3 (alpha) and the problem goes away.

