I’m using SVector and SMatrix classes to do vector algebra instead of CLHEP vectors and matrices in my new project. In general I am happy with them, but I ran into a curious problem when I wrote something like the following: SVector a,b,c; c = a + b; That code compiles and ‘runs’, even though SVector documentation and SVector.h don’t mention operator +. The call produces a resultant object ‘c’ object without numerical payload, just a pair of references to ‘a’ and ‘b’. I’m wondering if this is an undocumented feature of SVector, or if the compiler just invented this. I get the same results using both gnu g++ and clang.
Good to hear from you Lorenzo, I hope you’re well.
Thanks for the pointer to the operators, I missed that.
I ran into this because of a use case where the result of the addition had a longer lifetime than the operands, so by the time I used the result the operands had passed out of scope and the
vector expression gave erroneous values. I got around this using operator += instead. Is there a reason the binary operators return vector expressions instead of normal objects?
It is correct that in some cases the operands goes out of scope and the resulting vector expression contains references to deleted objects. This happens for example when using the auto keyword, see
The reason to return expressions is that operations can be combined and chained together at compiled time without creating temporary vector and matrices objects, making the computation more efficient.
This is the basics of the design of Vector and SMatrix that are based on expression templates