In the book The C++ Standard Library at page 91 I have read this about shared_from_this()
:
The problem is that
shared_ptr
stores itself in a private member ofPerson
’s base class,enable_shared_from_this<>
, at the end of the construction of the Person.
The relevant code snippet from the book is:
class Person : public std::enable_shared_from_this<Person> {
...
};
I don't understand two things here:
- who is this
shared_ptr
which stores itself? - how he can store itself anywhere at the end of the construction of
Person
? I think construction ofPerson
ends up with the last statement of its constructor which written by me.
I understand that there is weak_ptr
which hasn't been initialized yet.
EDIT:
Thanks to Angew! shared_from_this
will work only after first shared_ptr
to Person
was created. This shared_ptr
will check if Person
class inherited from enable_shared_from_this
, and if yes then initialize its internal weak_ptr
.