class father {
public:
father() {
cout << "father !" << endl;
}
~father() {
cout << "~~~~~father !" << endl;
}
void setSon(shared_ptr<son> s) {
son = s;
}
private:
//shared_ptr<son> son;
weak_ptr<son> son; // 用weak_ptr来替换
};
class son {
public:
son() {
cout << "son !" << endl;
}
~son() {
cout << "~~~~~~son !" << endl;
}
void setFather(shared_ptr<father> f) {
father = f;
}
private:
shared_ptr<father> father;
};
void test() {
shared_ptr<father> f(new father());
shared_ptr<son> s(new son());
f->setSon(s);
s->setFather(f);
}
int main()
{
test();
return 0;
}
输出:
father !
son !
~~~~~~son !
~~~~~father !