Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
A pitfall in C++ that I didn't see mentioned in the other answer is that it might give unexpected results with libraries using expression templates. What are expression templates? In a nutshell, ...
Answer
#1: Initial revision
A pitfall in C++ that I didn't see mentioned in the other answer is that it might give unexpected results with libraries using expression templates. ## What are expression templates? In a nutshell, expression templates are a technique that allows to write efficient numeric code with intuitive notation. Consider for example a matrix library with straightforward implementation using operator overloading. Then when you write e.g. ```c++ Matrix A = B + C + D ``` where `B`, `C` and `D` are also of type `Matrix`, what will happen is that `B + C` will generate a temporary matrix, which then is passed to the `second operator+` as first argument, where the second argument is C; this will then generate yet another temporary matrix that is used to initialise `A`. Now with move semantics, one may actually get rid of the temporary storage (I've not checked if that is actually possible), but the fact remains that the order of accesses will be very cache-unfriendly. Now one way to solve this is to have instead a function that directly implements the optimal access sequence (and also ensures no temporary storage even without optimisations): ```c++ add_three_matrices(A, B, C, D); ``` however that doesn't give the nice intuitive syntax. Now what expression templates do if that the expression 'A + B + C' does not actually calculate the sum, but creates an object built from templates that represents the expression, and initialising the Matrix A then triggers the actual, optimised code. That is, you can now write ```c++ Matrix A = B + C + D ``` and still get the optimised code. ## How does `auto` affect this? One might think that ```c++ auto A = B + C + D ``` gives equivalent code to the one above, but that is not the case. Instead `auto` is determined to be the expression template type *describing* the operation. This is particularly bad if the expression contains some actual temporary that will have been destroyed at the end of the statement; say you are scaling `D` with a double returned from a function: ```c++ auto A = B + C + D*f(x) ``` The return value of `f` is bound to a reference inside the expression, but since that reference is not A, but some reference inside the expression, it won't extend the life time of the temporary. So if `A` is ever used later (in a way that actually triggers the calculation), it will access a dangling reference.