This post is centered on “stack-use-after-scope” which is an issue we see often in code review and code sanitizer / valgrind reports. Here’s an example:
struct SimpleCalc{
SimpleCalc( const std::vector<int>& my_vec ) :
m_vec (my_vec) {};
int calculate() {
// Uses the m_vec and its content.
};
private:
const std::vector<int>& m_vec;
};
// < some code >
// Solution #1
SimpleCalc my_calc( std::vector<int>{ /*some values*/ } ); // <- Problem here.
// The temp created in the argument will have it's
// lifetime end with this full expression.
my_calc.calculate(); // Stack-use-after-scope.
The first/simplest solution (let’s call it solution 1) that usually comes to mind is to create an lvalue and pass it to the constructor, as such: