【发布时间】: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<C*>?您的应用程序中的哪些功能不适用于普通的shared_ptr<C>? -
离题但是... 将
std::shared_ptr指向指针类型(例如std::shared_ptr<B *>而不是std::shared_ptr<B>)的目的是什么?为什么需要额外的间接级别?
标签: c++ c++11 shared-ptr smart-pointers