weak_ptr 设计的目的是为配合 shared_ptr 而引入的一种智能指针来协助 shared_ptr 工作, 它只可以从一个 shared_ptr 或另一个 weak_ptr 对象构造, 它的构造和析构不会引起引用记数的增加或减少. 同时weak_ptr 没有重载*和->但可以使用 lock 获得一个可用的 shared_ptr 对象。 测试代码:
#include <stdio.h> #include <iostream> #include <string> #include <memory> #include <vector> using namespace std; class girl; class boy { public: boy() { cout << "boy construct!" << endl; } ~boy() { cout << "boy destruct!" << endl; } void set_girl_friend(shared_ptr<girl>& g) { this->girl_friend = g; } private: shared_ptr<girl> girl_friend; }; class girl { public: girl() { cout << "girl construct !" << endl; } ~girl() { cout << "girl destruct!" << endl; } void set_boy_friend(shared_ptr<boy>& b) { this->boy_friend = b; } private: shared_ptr<boy> boy_friend; }; void use_trap() { shared_ptr<girl> sp_girl(new girl()); /* 白娘子 */ shared_ptr<boy> sp_boy(new boy()); /* 许仙 */ sp_girl->set_boy_friend(sp_boy); sp_boy->set_girl_friend(sp_girl); } int main() { use_trap(); system("pause"); return 0; }执行: 修改测试代码:
#include <stdio.h> #include <iostream> #include <string> #include <memory> #include <vector> using namespace std; class girl; class boy { public: boy() { cout << "boy construct!" << endl; } ~boy() { cout << "boy destruct!" << endl; } void set_girl_friend(shared_ptr<girl>& g) { this->girl_friend = g; } private: shared_ptr<girl> girl_friend; }; class girl { public: girl() { cout << "girl construct !" << endl; } ~girl() { cout << "girl destruct!" << endl; } void set_boy_friend(shared_ptr<boy>& b) { this->boy_friend = b; } private: shared_ptr<boy> boy_friend; }; void use_trap() { shared_ptr<girl> sp_girl(new girl()); /* 白娘子 */ shared_ptr<boy> sp_boy(new boy()); /* 许仙 */ sp_girl->set_boy_friend(sp_boy); //sp_boy->set_girl_friend(sp_girl); } int main() { use_trap(); system("pause"); return 0; }画图理解: 老师的讲解:
执行修改的测试代码
弱指针主要是为了解决, 交叉引用
时间: 2020-07-04