c++ - shared_from_this() 如何在继承自基类的派生类中工作,该基类继承自 enabled_shared_from_this

标签 c++ inheritance shared-ptr

我想知道我对 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/

相关文章:

c++ - ./lib/gcc/x86_64-linux-gnu/4.6/libstdc++.a 的用法是什么

java - 为什么不使用工具来扩展工作?

在 boost::shared_ptr operator bool() 上旋转时需要 C++ volatile?

c++ - 在文本冒险中实现实时?

c++ - 为什么我的分析类非常慢?

c++ - 如何在 C++ 中循环创建形状并将其附加到窗口?

java - 在抽象类中持有对多个对象的静态引用可以吗?

c++ - 在派生类中添加虚拟说明符

c++11 - 用 std::unique_ptr/std::shared_ptr 确认线程安全

c++ - 1000个共享指针占用多少内存?