dimanche 24 mars 2019

Is it OK to use reference to the object owned by a shared_ptr?

I found this is working well but don't know if this is safe as I don't understand why it works:

struct X{
 static X& make(){
    return *std::make_shared<X>();
 }
}

int main(){
   const auto& a = X::make();
   a.function();
   ...
   // seems like the instance holds and nothing broken
}

In my understanding, the returned reference to the derefed object out of shared_ptr operator* should not impact how shared_ptr to manage the instance's reference count, so the created instance inside make() should be destroyed after make() is done. But this pattern of code has been working well for many times and I don't see why. So I'm not sure if we can really do it in this way... appreciate any comments!

Aucun commentaire:

Enregistrer un commentaire