#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;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.

输出:

aobj use count:1
bobj use count:1
请按任意键继续. . .
  • 1.
  • 2.
  • 3.

可见,这样的引用计数两个对象各还有一个。将一个对象的share_ptr改成weak_ptr就可以了。