jeudi 26 septembre 2019

boost::weak_ptr to a default constructed Object : lock() method returns a NULL pointer when a similar empty shared_ptr is expected

I have a bit of code where the original object is default constructed:

SimulatedIndexFixingStore::SimulatedIndexFixingStore() : Singleton<SimulatedIndexFixingStore>(),
        simulatedFixings_(Dictionary())
        {}

Dictionary is a typedef to a complicated unordered_map of map of map.

My decision is to use weak_pointers instead of shared ones to manage the proper deletion of static singleton instances at the end of my program. In the below bit:

 boost::weak_ptr<SimulatedIndexFixingStore>& simulatedIndicesFixings_; <--- default constructed using SimulatedIndexFixingStore()

auto p = simulatedIndicesFixings_.lock(); <--- here the shared ptr p has a NULL pointer!

My understanding from reading lock() definition on cppreference is when an object is default constructed, I would get a shared_ptr p that points to an empty object, but not a NULL pointer!

Whereas, looking inside the boost implementation of weak_ptr, it makes perfect sense:

template<class Y>
    shared_ptr( weak_ptr<Y> const & r, boost::detail::sp_nothrow_tag )
    BOOST_NOEXCEPT : px( 0 ), pn( r.pn, boost::detail::sp_nothrow_tag() )
    {
        if( !pn.empty() ) // px is left null if the object pn points is empty/default
        {
            px = r.px;
        }
    }

Is my understanding correct? Is there a difference in implementation between the two libraries? If so, can you please let me know of any other way to re-use my weak_ptr to the default constructed object in later code, other than having to use the std::weak_ptr implementation.

Thanks

Amine

Aucun commentaire:

Enregistrer un commentaire