Reputation: 4849
Could someone explain why the following crashes? I'm using enable_shared_from_this so that bob does not get deleted.
class Person : public std::enable_shared_from_this<Person> {
private:
std::string name;
public:
Person (const std::string& name) : name(name) {}
std::string getName() const {return name;}
void introduce() const;
};
void displayName (std::shared_ptr<const Person> person) {
std::cout << "Name is " << person->getName() << "." << std::endl;
}
void Person::introduce() const {
displayName (this->shared_from_this());
}
int main() {
Person* bob = new Person ("Bob");
bob->introduce(); // Crash here. Why?
}
Upvotes: 3
Views: 2912
Reputation: 2151
One of the preconditions of shared_from_this
is that the object (this
) has to be already owned by some shared_ptr
. It then returns a shared_ptr
that shares ownership with the already existing shared_ptr
.
Because your object is not owned by any shared_ptr
when calling shared_from_this
, you are invoking undefined behaviour (it crashes).
Try this instead:
int main() {
auto bob = std::make_shared<Person>("Bob");
bob->introduce();
}
Upvotes: 7
Reputation: 9648
The documentation states:
Before calling
shared_from_this
, there should be at least onestd::shared_ptr<T> p
that owns*this
.
So if we change main()
to:
std::shared_ptr<Person> bob( new Person ("Bob") );
bob->introduce();
there will be no issue since there is already a shared_ptr
that owns *this
Upvotes: 4