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