-
Notifications
You must be signed in to change notification settings - Fork 69
Pitfalls & gotchas
Given that Fastor is an expression template math library there are certain idioms and rules you have to follow while writing code that uses Fastor. In particular
C++11 and more specifically C++14 allows the use of auto
return keyword in functions. Consider
auto add() {
Tensor<double,3,3> a,b;
return a+b;
}
While there seems nothing incorrect in this function, you have to keep in mind that Fastor's expressions are not evaluated immediately in to a tensor. In the above example the addition between two tensors a+b
does not result in a tensor. It results in an "addition expression" that holds references to tensors a
and b
. As a result the return type of this function is deduced to be an expression owing to the use the keyword auto
and given that both a
and b
are local to this function the references contained in this addition expression will be dangling once you exit the scope of the function. So calling this function will not give the expected result
Tensor<double,3,3> c = add();
To fix this you can either change the return type of the function from auto
to an appropriate tensor
Tensor<double,3,3> add() {
Tensor<double,3,3> a,b;
return a+b;
}
or if you must use the keyword auto
then you can call the evaluate
function on the expression on return
auto add() {
Tensor<double,3,3> a,b;
return evaluate(a+b);
}
Both these strategies will give the expected result.