jeudi 17 juin 2021

creating a member class shared_ptr

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);

I have created 2 classes B and C. In B, there is a shared_ptr to C. In main I create a shared_ptr of B. From the object of B , i.e, bb, I can not initialize that shared_ptr of C.

Aucun commentaire:

Enregistrer un commentaire