I know that I can "promote" weak_ptr
to shared_ptr
like that:
// std::weak_ptr<T> weak;
std::shared_ptr<T> promoted(weak);
My question is: can that be prevented somehow?
As an exercise I wanted to create my own veeery simple implementation of a WeakPtrFactory. It is initiated with this
as a class member, and then spawn weak_ptr
s which will be invalidated on object's destruction. My attempt simply used shared_ptr
as private member and returned weak_ptr
s created with it (no op deleter is passed just in case). But it has obvious disadvantage since everyone can just promote them back to shared_ptr
and break whole mechanism.
Following @user2357112 advice I've wrapped std::weak_ptr
to internally create std::shared_ptr
when needed and destroy it right after use.
I should probably clarify that what I wanted to achieve was simplified version of this concept. Though it has the similar name this WeakPtr
has a different use case to the shared_ptr
's one. It is used to check in a non-thread safe way that some object was/wasn't destroyed, so that we could take actions appropriately. It is programmers responsibility to make sure that if object is still alive he can safely use it (e.g. by forcing to checking its existence and calling its methods on the same thread).