2

Need your help here,

int main()
{
    std::unique_ptr<int> p(std::make_unique<int>(50));

    auto func = [](std::unique_ptr<int>& ptr)
    {
        std::this_thread::sleep_for(std::chrono::seconds(5));
        std::cout << *ptr << std::endl;
    };

    std::thread t(func,std::ref(p));
    t.detach();
}

I am deliberatly waiting for 5 secs (although 0,1 sec is enough as well) so that the p is deleted after main() returns.
And after main() returns the thread cannot access the local object because its destructed right?
But is this case I have the following output:

Press any key to continue... 50

Can anyone explain why thread can read the deleted pointer?

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • 6
    Undefined behavior can appear to work. Crashes on my machine. – Eljay Mar 20 '20 at 15:22
  • 1
    I upvoted, because this was an interesting puzzle and I've learned things. I've had different results on my machine: a.out has crashed, it has printed 50, it has printed 2, and it has terminated without printing anything. – Eljay Mar 20 '20 at 15:49

0 Answers0