CRTP: Compiler dependent issue with Expression Template

倾然丶 夕夏残阳落幕 提交于 2019-12-01 12:55:51

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!