Lesson learned: Do Not Store rvalue Reference Outlive its Declaration

I am building a custom operator overloading structures in C++, and was really seduced with what rvalue promises: the lifetime of rvalue reference is bound to the expression of its context.

Rvalue references can be used to extend the lifetimes of temporary objects (cppreference.com)

I was building a combination of operators which accepts a lot of literals and temporary objects including lambda. So for instance:

auto res = ObjectA() * ObjectB() + ObjectC() * ObjectD();

Based on the precedence rules, ObjectA will be ‘multiplied’ with ObjectB, then ObjectC will be ‘multiplied’ with ObjectD, then the result object of those two will be ‘added’. Notes that the order of multiplication is decided by compiler.

So the thing is, inside the overloaded multiplication operator, I want to store the temporary ObjectD, for instance, then carry it over on the addition operator later on when executing the ‘add’ operator. To achieve the “efficiency”, I store the ObjectD temporary inside an rvalue reference so it can be accessed “efficiently” during the execution of the ‘add’ operator.

Continue reading “Lesson learned: Do Not Store rvalue Reference Outlive its Declaration”