【问题标题】:Understanding the class shared pointers and its use in inheritance了解类共享指针及其在继承中的使用
【发布时间】:2019-08-08 20:19:12
【问题描述】:

我很难理解下面给出的这段代码。

class Child1 : public Base1 {
public:
    int Func1(char *Var);
}

class Cls_X: public std::enable_shared_from_this<Cls_X> {
public:
    void Func2(char *Var_copy);
}

Func2Func1 调用如下

int Func1(char * Var){
    ...
    make_shared<Cls_X>(ioc, ctx)->Func2(Varcopy_ptr);
    ...
}

问题:

  • class Cls_X: public std::enable_shared_from_this&lt;Cls_X&gt; 是如何工作的? 尝试谷歌搜索但无法理解相关文档,有人可以用简单的英语解释一下吗?

  • Cls_X 和 Child1 都是 Base1 的派生类吗?

注意:

添加标签 [boost] 是因为 code example 取自 boost 库之一。请查看示例以了解程序中如何使用shared_from_this

Ps 1:-尽可能更改合适的标题。

【问题讨论】:

  • 要了解它,您必须先了解Curiously Recurring Template Pattern (or CRTP)
  • 另外,对于这里显示的简单案例,我看不出有任何理由使用std::enable_shared_from_this 或共享指针(或任何类型的指针)。为什么不直接做Cls_X(ioc, ctx).Func2(Varcopy_ptr);?考虑到所创建对象的临时性和临时性,Cls_X 是否需要成为一个类? Func2 不能成为非成员函数吗?可能使用iocctx 作为额外参数?
  • 您的示例并未真正展示其用途。 enable_shared_from_this 顾名思义就是从this 获取共享指针。您的示例可以在不继承 enable_shared_from_this 的情况下工作
  • @Someprogrammerdude 实际上这篇文章是故意使看起来简单并专注于(我的)困惑。作为参考,我在 Ps 1 中添加了指向几乎相似代码的链接。这将回答您的疑问“Cls_X 是否需要成为一个类”。我正在通过en.wikipedia.org/wiki/Curiously_recurring_template_pattern
  • 我建议你重新表述问题,因为现在你可以放心地忽略Cls_X 继承自enable_shared_from_this 的事实,实际上没有必要理解代码 sn-p,虽然我觉得这是你真正想问的问题

标签: c++ inheritance boost shared-ptr


【解决方案1】:

class Cls_X: public std::enable_shared_from_this&lt;Cls_X&gt; 是如何工作的?

它可以工作iff模板类的特化(这里是std::enable_shared_from_this&lt;Cls_X&gt;)不需要接收一个完整类型的类型参数(这里是Cls_X)。

template <typename T>
struct has_a_member { T mem; };

template <typename T>
struct has_a_pointer { T *ptr; };

struct A : has_a_member<A> // error at this point: 
                           // A is incomplete at this point
                           // the definition of has_a_member<A> cannot be instantiated 
{
};

struct B : has_a_pointer<B> // OK, B is incomplete 
                            // still has_a_pointer<B> can be instantiated
{
};

enable_shared_from_this 被设计为在这种情况下工作,期望一个不完整的类型。

【讨论】:

    猜你喜欢
    • 2020-05-03
    • 2011-06-10
    • 1970-01-01
    • 2019-08-31
    • 2011-02-11
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多