Reputation: 149
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
manages 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!
Upvotes: 2
Views: 116
Reputation: 36503
No, the shared pointer returned from make_shared
is instantly destroyed after the return and thus the reference obtained by dereferencing it will be dangling. It might look like it works but it really is just undefined behavior, and as said in the comments undefined is undefined.
Upvotes: 8