If I want to return a shared_ptr for class A, I should use shared_from_this() feature. But I think this will work after I defined a shared_ptr for A already. So if another place wants a shared_ptr I just use the one I made. I wonder when to use shared_from_this().
sample code:
class A : public enable_shared_from_this<A> {
public:
int a = 0;
shared_ptr<A> get_this() {
return shared_from_this();
}
};
int main() {
shared_ptr<A> ptr_a(new A);
cout << ptr_a.use_count() << endl;
shared_ptr<A> ptr_b = ptr_a->get_this();
// if somewhere else wants a ptr I just use, shared_ptr<A> ptr_b = ptr_a; after pass it
// into a function, what situation should i use shared_from_this() for instead ???
cout << ptr_a.use_count() << endl;
cout << ptr_b.use_count() << endl;
}
You appear to have a misunderstanding about
shared_ptrandshared_from_this.You don't need to use
shared_from_thisin order to retrieve ashared_ptrif you already have one. In your example, you could just do:However, there are cases where a design requires that a class be aware of its shared lifetime -- and must be able to retrieve a
shared_ptrto itself. In such a case, you can't simply do:std::shared_ptr<A>{ this }because this would be producing a newshared_ptrnode that is tracking the pointer ofthis-- which could result in a bad/double deletion.shared_from_this()solves this by allowing the internals of the class to be able to retrieve safeshared_ptrobject to the object that was allocated. In my experience, this pattern is most common with asynchronous callback handlers. For example:Note: I am not advocating for this style of code; just that this is a possible use for it. In general I find it better to design classes such that it never relies on knowing its own lifetime.