Temporary objects: lifetime and Extensions – part 2


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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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:

Continue reading “Temporary objects: lifetime and Extensions – part 2”