Cyphall
Cyphall

Reputation: 368

"Address of local variable may escape the function" in range-based for loop

I want to store a pointer to a vector element, selected in a range-based for loop, all that in a static context.
However, CLion gives me the warning Address of local variable may escape the function.

Here is an example:

struct TestStruct
{
    static std::vector<std::string> _values;
    static const std::string* _selectedValue;
    
    static void selectValue()
    {
        for (const std::string& value : _values)
        {
            if (value == "toto")
            {
                _selectedValue = &value; // The warning is here, on the "&value" part.
            }
        }
    }
};

When removing the three static keywords however, the warning goes away.

When I run the static and non-static versions, it work as expected in both cases, as the for loop uses references to elements.

Why is this warning present in the static version?
Is there something special about static variables lifetime that could make this not work?

Upvotes: 2

Views: 2328

Answers (1)

Nikola Dimitroff
Nikola Dimitroff

Reputation: 6237

There's nothing wrong with the code as it stands in terms of object lifetime.

CLion isn't omnipotent - it doesn't know what your intent is. What it knows, is that you are storing the address of a local variable (value) in a static var so it's completely right at warning you that "The address of a local variable may escape the function". Whether that's an issue, depends on your intent and as the code stands it looks fine.

I would mention that you need to be extra careful with this construct however as most modifications of the vector will cause the pointer to start pointing to another element or invalid memory. In general this code is very error prone unless you initialize the data in the vector at the start of the program and shut it down before exiting the program without any changes in the interim.

Upvotes: 4

Related Questions