0

Consider the following code:

void g(std::vector<int>& V) 
{
    std::this_thread::sleep_for(std::chrono::seconds(2));
    for (int i = 0; i < 100; ++i) { V.push_back(i); }
    for (int i = 0; i < 100; ++i) { std::cout<<V[i]<<" "; }
}

void f() 
{
    std::vector<int> V;
    auto fut = std::async(std::launch::async, g, std::ref(V));
    std::cout << "end of f" << std::endl;
}

int main() {
    f();
    system("pause");
}

When I run the program, it prints end of f then waits 2 second then prints 0 1 2 3 4 5 6 7 8 9. My question is - if I pass V as a reference with std::ref and after the scope of f() it should be deleted. So how the program pushes and access to V when V is deleted after f()?

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • 9
    Accessing a destructed object leads to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior), and UB makes all discussion about behavior moot. UB is UB, sometimes it might *seem* to work, while other times you get [nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html). – Some programmer dude May 20 '18 at 20:11
  • I use VS2017, and I just want to confirm that the program is ill formed, the V shoulnt be passed as reference, or get must be called before f ends, right? – Eduard Rostomyan May 20 '18 at 20:13
  • 1
    @Eduard Rostomyan the compiler is *not* required to tell you when you break the rules of the language (engage in UB). It is allowed to just silently assume you didn't do so and generatd *some* code - nonsensical or not. It's all on *you* not to write code with UB. – Jesper Juhl May 20 '18 at 20:31

0 Answers0