Why shared_from_this can't be used in constructor from technical standpoint?

后端 未结 1 697
悲&欢浪女
悲&欢浪女 2020-11-27 20:51

In the book The C++ Standard Library at page 91 I have read this about shared_from_this():

The problem is that shared_ptr st

相关标签:
1条回答
  • 2020-11-27 21:23

    The reason is simple: in object X, enable_shared_from_this works by initialising a hidden weak_ptr with a copy of the first shared_ptr which points to object X. However, for a shared_ptr to be able to point to X, X must already exist (it must be already constructed). Therefore, while the constructor of X is running, there is yet no shared_ptr which enable_shared_from_this could use.

    Take this piece of code:

    std::shared_ptr<Person> p(new Person());
    

    Before the constructor of p (of the shared_ptr) is even called, its argument must be evaluated. That argument is the expression new Person(). Therefore, the constructor of Person runs before the constructor of p has even begun—before there is any shared_ptr object to which enable_shared_from_this could bind.

    0 讨论(0)
提交回复
热议问题