【问题标题】:I cannot initialize that shared_ptr of class C我无法初始化 C 类的 shared_ptr
【发布时间】:2021-09-02 20:52:34
【问题描述】:
class B;
class C;

class B
{
  public:
    B() { cout<<"B created"<<endl; }
    ~B() { cout<<"B destroyed"<<endl; }

    shared_ptr<C*> ptrc;
};

class C
{
  public:
    C() { cout<<"C created"<<endl; }
    ~C() { cout<<"C destroyed"<<endl; }
};

int main()
{
    shared_ptr<B*> bb = make_shared<B*>(new B);
    bb->ptrc = make_shared<C*>(new C);// this line gives error
}
error:
a.cpp: In function ‘int main()’:
a.cpp:133:9: error: request for member ‘ptrc’ in ‘*((std::__shared_ptr_access<B*, __gnu_cxx::_S_atomic, false, false>*)(& bb))->std::__shared_ptr_access<B*, __gnu_cxx::_S_atomic, false, false>::operator->()’, which is of pointer type ‘std::__shared_ptr_access<B*, __gnu_cxx::_S_atomic, false, false>::element_type’ {aka ‘B*’} (maybe you meant to use ‘->’ ?)
      133 |     bb->ptrc = make_shared<C*>(new C);

我创建了 2 个类 B 和 C。在 B 中,有一个 shared_ptr 到 C。在 main 中,我创建了 B 的 shared_ptr。从 B 的对象,即 bb,我无法初始化 C 的 shared_ptr。

【问题讨论】:

  • 你为什么有shared_ptr&lt;C*&gt;?您的应用程序中的哪些功能不适用于普通的shared_ptr&lt;C&gt;
  • 离题但是... 将std::shared_ptr 指向指针类型(例如std::shared_ptr&lt;B *&gt; 而不是std::shared_ptr&lt;B&gt;)的目的是什么?为什么需要额外的间接级别?

标签: c++ c++11 shared-ptr smart-pointers


【解决方案1】:

bb 是指向指针 B*shared_ptr,即几乎是指向指针的指针。你可以像这样取消引用它

(*bb)->ptrc = make_shared<C*>(new C);

但是,您的代码存在内存泄漏,new 创建的对象不是deleteed。这里失去了使用智能指针的主要目的。只是不要使用shared_ptr 指向指针,而是直接使用BC 之类的类,例如

shared_ptr<B> bb = make_shared<B>(); // bb is a shared_ptr to B
bb->ptrc = make_shared<C>(); // declare ptrc as shared_ptr<C> too

【讨论】:

    【解决方案2】:

    shared_ptr 用于处理对象,而不是指针 - 因此无需声明 shared_ptr&lt;B*&gt;shared_ptr&lt;C*&gt;:您可以使用 shared_ptr&lt;B&gt;shared_ptr&lt;C&gt;。这意味着初始化代码应该是:

    int main()
    {
        shared_ptr<B> bb = make_shared<B*>();
        bb->ptrc = make_shared<C>();// this line gives error
    }
    

    这会产生预期的输出:

    B created
    C created
    B destroyed
    C destroyed
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      相关资源
      最近更新 更多