0

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_ptrs which will be invalidated on object's destruction. My attempt simply used shared_ptr as private member and returned weak_ptrs 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.

Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64
  • The conversion to `shared_ptr` is intended to prevent the object from being deleted while some code is in the middle of using it. If you assume that will never happen, there's not that much benefit to using a weak pointer over just a regular pointer. – user2357112 Jul 30 '14 at 13:27
  • Benefit is that you are able to check safely if object wasn't deleted. If object is selfmanaging (e.g. some task), does some work, and then commits suicide, it would be nice to know whether or not you are still able to ask it to do something for you. That's one way Chromium uses `weak_ptr`s. A bit broader usage that simple "break `shared_ptr` dependency circle" thing. – Mateusz Kubuszok Jul 30 '14 at 13:34
  • 1
    Well, if you want to use `std::weak_ptr` in your implementation, you're going to have to wrap it in something that handles the `shared_ptr` conversion and doesn't let it escape, because the only way to dereference a `std::weak_ptr` is to get a `std::shared_ptr` from it first. – user2357112 Jul 30 '14 at 14:46

1 Answers1

0

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).

Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64