Question

What if I create new class based on std::enable_shared_from_this. And store it's shared_from_this() method result as a member std::shared_ptr:

class B : public std::enable_shared_from_this<B> {
    public: 
        B(){
           sharedThisPtr_ = shared_from_this();
        }

    private:
        std::shared_ptr<B> sharedThisPtr_;

    };

Will such class object will be ever destructed and deallocated?

int main(void){
    auto myObj = std::make_shared<B>();
}
Was it helpful?

Solution

This won't work, even after fixing the syntax error: shared_from_this requires that there be at least one shared_ptr instance that owns *this. During initialisation, no shared_ptr owns it.

You might get an exception, an empty shared pointer, or some other kind of undefined behaviour.

If you were to set sharedThisPtr later, once myObj owns it, then it would act like any other shared pointer, preventing destruction as long as it shares ownership of the object. So, in that case, the object will never be destroyed unless you reset sharedThisPtr.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top