Search code examples
c++shared-ptr

Way to check if calling shared_from_this() is valid?


I'd like to use shared_from_this() to get a std::shared_ptr from an object that was passed by reference. However, I'd like to be robust to objects which might not be in a shared pointer, or which might not even be dynamically allocated.

Is there a way to check if a given object (inheriting from enable_shared_from_this and passed by reference) is managed by a shared pointer prior to invoking the potentially undefined behavior of calling shared_from_this()?


Solution

  • You can implement your own make_shared, shared_from_this, and enable_shared_from_this that has whatever semantics you want. Implementing the semantics you ask for is not difficult:

    1. The class should hold a weak_ptr to the instance of the class it's templated on.

    2. The make_shared implementation should initialize the weak pointer from the shared_ptr it creates first.

    3. The shared_from_this should attempt to lock the weak pointer and return an empty shared_ptr if it fails.

    Alternatively, if weak_from_this is available on your platform (it's a C++17 feature), you can just use that.

    But, as others have said, it seems very hard to believe that this really is the best solution to whatever problem you're having. The cases where you need shared_from_this to work would have to perfectly align with the cases where shared_from_this will work. It's hard to imagine a use case where that's the case.