3

Normally, I'd omit the std::vector but that would require me to make my function take a const int&. What I want to know is since there's a temporary vector if I have a dangling reference. Is it safe to modify its elements?

#include <iostream>
#include <vector>

void foo(int& i)
{
    i = 42;
}

void foo(int&& i)
{
    std::cout << "int&&";
}

int main()
{
    for (auto&& i : std::vector<int>{1, 2, 3})
    {
        foo(std::forward<decltype(i)>(i));
    }
}

1 Answers1

2

Your temporary vector survives for the lifetime of the loop, due to the way in which the ranged-for statement is defined. Therefore, there are no dangling references here and your program is safe. Modify away.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055