CRTP: Compiler dependent issue with Expression Template

后端 未结 1 1575
独厮守ぢ
独厮守ぢ 2021-01-15 22:48

I incurred in a compiler dependent issue with the following code (stored in crtp.cc):

#include 
#include 
#include 

        
相关标签:
1条回答
  • 2021-01-15 23:15

    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.

    0 讨论(0)
提交回复
热议问题