I'm using enable_shared_from_this<Base>
and then inherit from Base
. When trying to use shared_from_this()
in Derived
's constructor (not initializer list), I get an exception. Turns out that the internal weak pointer is null and doesn't point to this
at all. How can this happen? My other use case of exactly this works perfectly fine. I don't even know where to start. I looked down at the source code of enable_shared_from_this
, and it looks to me like that pointer would always be nullptr.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Conceptually,
shared_from_this()
picks ashared_ptr
pointing tothis
and returns a copy of it.In the constructor, there is no
shared_ptr
pointing tothis
.You cannot call
shared_from_this()
in the object's constructor.shared_from_this()
requires that the object is owned by at least oneshared_ptr
. An object cannot be owned by ashared_ptr
before it is constructed.I would guess that the internal weak pointer is set when a
shared_ptr
takes ownership of the object for the first time. Before that point, there is no reference count struct that the weak pointer can reference.James McNellis's answer is right.
As for the explanation of the
enable_shared_from_this
template itself, which as you observe appears to do nothing, note 7 at the bottom of this page explains: