#include <iostream>
#include <string>
#include <memory>
using namespace std;
namespace
{
class B;
class A
{
public:
std::shared_ptr<B> pb;
};
class B
{
public:
std::shared_ptr<A> pa;
};
}
int main()
{
shared_ptr<A> *spa = nullptr;
shared_ptr<B> *spb = nullptr;
{
shared_ptr<A> aobj(new A);
shared_ptr<B> bobj(new B);
spa = &aobj;
spb = &bobj;
aobj->pb = bobj;
bobj->pa = aobj;
}
cout << "aobj use count:" << spa->use_count() << endl;
cout << "bobj use count:" << spb->use_count() << endl;
system("pause");
return 0;
}
輸出:
aobj use count:1
bobj use count:1
請按任意鍵繼續. . .
可見,這樣的引用計數兩個物件各還有一個。將一個物件的share_ptr
改成weak_ptr
就可以了。