Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

His last fix is buggy:

    if( !pMaverick->myWingMan.expired() )
    {
        cout << pMaverick->myWingMan.lock()->m_flyCount << endl;
    }
The problem here is it will still crash if another thread destroys the object between line #1 and line #3.

Here’a good fix, from http://en.cppreference.com/w/cpp/memory/weak_ptr/lock

    if( auto observe = weak.lock() ) {
        std::cout << "\tobserve() able to lock weak_ptr<>, value=" << *observe << "\n";
    }
    else {
        std::cout << "\tobserve() unable to lock weak_ptr<>\n";
    }



Yep - thanks for calling this out. I should have put out a version that's safe in multithreaded environment. I've updated the article to reflect this.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: