vard
vard

Reputation: 2302

store enable_shared_from_this based class pointer(this) within itelf

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>();
}

Upvotes: 1

Views: 709

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254771

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.

Upvotes: 4

Related Questions