我想知道我对 shared_ptr
的理解是否最新和 shared_from_this()
工作原理以及内存分配的工作原理。
以下是我的类(class):
class Component : public enable_shared_from_this <Component>
{
public:
Component() :enable_shared_from_this(){}
};
class DerivedComponent : public Component
{
public:
DerivedComponent()
{}
void tryDerivedShared()
{
auto sptr1 = shared_from_this();
if (this == sptr1.get())
std::cout << "Both have same starting address";
}
private:
std::vector<int> myVector;
};
int main()
{
auto sptr = make_shared<DerivedComponent>();
sptr->tryDerivedShared();
}
当我从基类派生时,我的理解是内存首先分配给基类,然后分配给派生类。所以当我做
auto sptr1 = shared_from_this();
会发生什么它返回 shared_ptr
到基类 Component 的对象。由于基是 Derived 类的内存的一部分,this == sptr1.get()
的值是 true
因为它们都返回了它们指向的 obj 的起始内存。基本上分配的内存就像 |Base|Derived|和
shared_from_this()
返回 shared_ptr
仅指向 Base 的对象,即 |Base|一 block 内存。我的理解正确吗?
最佳答案
将这些类视为结构可能更容易。只有你的基类是空的,所以这可能不是最好的例子。
struct Component
{
};
派生时,实际上是在结构中添加字段,但您可能希望这样看待它:
struct DerivedComponent
{
struct Component component_;
std::vector<int> myVector;
};
因此,当您分配
DerivedComponent
时,您是正确的。 ,Component
的地址(或 &obj.component_
)都是一样的,这就是为什么你可以 static_cast<>()
两者之间。当你从许多类派生时,它变得更加复杂,特别是如果使用
virtual
关键词。另一方面,拥有虚函数并不太复杂,它在开头添加了一个虚表指针,但就您而言,指针是隐藏的。enable_shared_from_this()
不会改变这个概念。它只是添加了一个指向 Component
的弱指针。结构体。所以Component
类看起来更像这样:struct Component
{
struct enable_shared_from_this shared_;
};
关于c++ - shared_from_this() 如何在继承自基类的派生类中工作,该基类继承自 enabled_shared_from_this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39432594/