I incurred in a compiler dependent issue with the following code (stored in crtp.cc):
#include
#include
#include
You should always enable compiler warnings; they can often spot subtle problems. In this case:
g++ -Wall -Wextra test.cpp
test.cpp: In member function ‘const typename AlgebraicVectorExpression<AlgebraicVectorSum<T1, T2> >::ValueType& AlgebraicVectorSum<T1, T2>::operator[](typename AlgebraicVectorExpression<AlgebraicVectorSum<T1, T2> >::SizeType) const [with T1 = AlgebraicVector, T2 = AlgebraicVector]’:
test.cpp:90: instantiated from ‘AlgebraicVector::AlgebraicVector(const AlgebraicVectorExpression<T1>&) [with T = AlgebraicVectorSum<AlgebraicVector, AlgebraicVector>]’
test.cpp:103: instantiated from here
test.cpp:52: warning: returning reference to temporary
This tells you the problem:
const ValueType& operator[](SizeType ii) const {
return (a_[ii] + b_[ii]);
}
The result of the expression is a temporary, destroyed at the end of that line, so the function is returning a dangling reference to a non-existent object. This operator will have to return by value instead, and you shouldn't implement the non-const
overload since there is no value to modify.