SVector addition operator?

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.

Please read tips for efficient and successful posting and posting code

ROOT Version: Not Provided
Platform: Not Provided
Compiler: Not Provided

I think @moneta can give an explanation about this

Hi David,

The operator exists but it is implemented as a free operator , not as a member function, in the file BinaryOperations.h, see

Same thing is also for the SMatrix class and the other operators (-,*,/)


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?

thanks, Dave

Hi Dave,

I am well, I hope you are too.

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



This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.