Home >Backend Development >C++ >Why Can't `shared_from_this` Be Used in a Constructor?

Why Can't `shared_from_this` Be Used in a Constructor?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-08 12:32:02193browse

Why Can't `shared_from_this` Be Used in a Constructor?

shared_from_this Constructor Limitation: Technical Explanation

Unlike common misconceptions, the inability of shared_from_this to be used in a constructor stems from technical limitations. To understand why, we delve into the internals of its implementation.

shared_from_this relies on a private member in the base class, enable_shared_from_this, to store a weak_ptr. However, this weak_ptr is not initialized until the very end of the construction process. This means that when the constructor for the derived class (e.g., Person) is executing, there is yet no shared_ptr pointing to the object.

To illustrate this, consider the code snippet from the book:

class Person : public std::enable_shared_from_this<Person> {
   ...
};

The shared_from_this function within the Person class would attempt to initialize the hidden weak_ptr using the first shared_ptr that points to an object of type Person. However, as the constructor for Person is currently running, no such shared_ptr exists.

This technical restriction arises because the constructor for the shared_ptr must be called before any action is taken on the pointed-to object. Hence, the shared_from_this mechanism cannot operate within the constructor of the derived class, as there is no shared_ptr available at that stage.

The above is the detailed content of Why Can't `shared_from_this` Be Used in a Constructor?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn