문제

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>();
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top