Search code examples
c++vectorboostiteratorlocal-variables

Problems with returning references to local variables...?


There is a complaint that the following function doesn't work because it returns "pointers/iterators to local variables". Is this complaint correct? I can't see this problem...

const Range dummy::foo() const
{
    std::vector<Handle> _handles;
    _handles.reserve(_collection.size());

    for (const auto& pair: _collection)
    {
        _handles.push_back(pair.first);
    }

    return _handles;
}

Return type:

using Range = boost::any_range<Handle, boost::forward_traversal_tag, const Handle>;

Thanks for explanations and suggested solutions!


Solution

  • Is this complaint correct?

    Yes it is. _handles is an automatic variable, and you return a range referring to it. Ranges are basically abstractions over pairs of iterator + sentinel. The returned range will be invalid outside the function.

    And how can I solve this

    A correct implementation would be to return a transforming adaptor range. Possibly something along the lines of:

    return _collection | boost::adaptors::map_keys;