-1

Is it dangerous to return a reference wrapper like showed below:

std::vector<std::reference_wrapper<int>> foo() {

    int x = 10;

    std::vector<std::reference_wrapper<int>> vec;
    vec.push_back(x);
    return vec;

}

foo2() {
    std::cout << foo()[0] << std::endl;
}

I assume the local/stack variable x can be lost in foo2().

user1056903
  • 921
  • 9
  • 26

1 Answers1

1

Function std::vector<std::reference_wrapper<int>> foo(); essentially returns a vector with references to local variables located in function's stack which has been destroyed. A vector of dangling references. This is undefined behaviour.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271