I'm trying to understand cyclic reference with shared_ptrs In this case why there's no Circular reference as Com holds a Sup and from Sup is created a Com with Sup ? I would like to know what exactly happens to understand it better. Thanks you.
struct Com;
struct Sup: public std::enable_shared_from_this<Sup>
{
Sup(int id):id_(id)
{
std::cout<<"***CS: " << id_ << std::endl;
}
~Sup()
{
std::cout<<"###DestrSup " << id_ << std::endl;
}
void d()
{
auto com = std::make_shared<Com>(7, shared_from_this());
}
int id_;
};
using SupPtr = std::shared_ptr<Sup>;
struct Com
{
Com(int id, SupPtr supPtr):id_(id), supPtr_(supPtr)
{
std::cout<<"***ConstrCom: " << id_ << std::endl;
}
~Com()
{
std::cout<<"###DestrCom: " << id_ << std::endl;
}
int id_;
SupPtr supPtr_;
};
int main()
{
auto sup = std::make_shared<Sup>(1);
auto com = std::make_shared<Com>(1, sup);
auto com2 = std::make_shared<Com>(2, sup);
auto com3 = std::make_shared<Com>(3, sup);
sup->d();
return 0;
}