what is different in Paul Preney' code in Expression templates and C++11 that permits the temporary vectors to exist as long as the rvalue-references members exist?
Nothing permits such a thing.
The temporary vectors there exist until the end of the full expression, as any other temporary that isn't bound to a local reference variable. That is enough in Paul's code because the code immediately materialises the expression tree into an actual math_vector
, and the temporaries are not needed anymore after that.
Paul's code does not store any expression template node (math_vector_expr
) anywhere, while your code stores one (X
) as x2
. That's a known issue with auto
: it does the wrong thing when you are using expression templates because it results in storing the expression tree, which is likely to contain references that will become dangling right away.
In order to make it totally clear, the following is fine.
math_vector<3> result =
math_vector<3>{1.0, 1.1, 1.2} +
math_vector<3>{2.0, 2.1, 2.2} +
math_vector<3>{3.0, 3.1, 3.2} +
math_vector<3>{4.0, 4.1, 4.2}
; // no references are held to any temporaries past this point
The following is not fine.
math_vector_expr<3> result = // or auto
math_vector<3>{1.0, 1.1, 1.2} +
math_vector<3>{2.0, 2.1, 2.2} +
math_vector<3>{3.0, 3.1, 3.2} +
math_vector<3>{4.0, 4.1, 4.2}
; // result now holds references to those temporaries