C++ 中 shared_ptr weak_ptr
2022/7/24 1:25:08
本文主要是介绍C++ 中 shared_ptr weak_ptr,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
shared_ptr
std::shared_ptr<int> sp1 = new int(); // shared count = 1, weak count = 0 std::shared_ptr<int> sp2(sp1); // shared count = 2, weak count = 0 std::shared_ptr<int> sp3 = sp2; // shared count = 3, weak count = 0 std::weak_ptr<int> wp1(sp1); // shared count = 3, weak count = 1 std::weak_ptr<int> wp2(wp1); // shared count = 3, weak count = 2 std::weak_ptr<int> wp3 = wp2; // shared count = 3, weak count = 3
shared_ptr weak_ptr 使用 reset 或者指向另一个 managed object导致 shared count或weak count相应的减一。
- 类继承中使用shared_ptr
class Base {}; class Derived : public Base {}; ...... shared_ptr<Derived> dp1(new Derived); shared_ptr<Base> bp1 = dp1; shared_ptr<Base> bp2(dp1); shared_ptr<Base> bp3(new Derived);
- casting shared_ptr
shared_ptr<Base> base_ptr (new Base); shared_ptr<Derived> derived_ptr; // if static_cast<Derived *>(base_ptr.get()) is valid, then the following is valid: derived_ptr = static_pointer_cast<Derived>(base_ptr);
- make_shared
使用shared_ptr
make_shared 用法:
shared_ptr<Thing> p (make_shared<Thing>(42, "I'm a Thing!")); shared_ptr<Base> bp(make_shared<Derived1>()); // shared_ptr中的 template参数与make_shared中的tmeplate参数可以不一样(继承关系)
使用 weak_ptr
void do_it(weak_ptr<Thing> wp){ shared_ptr<Thing> sp = wp.lock(); // get shared_ptr from weak_ptr if(sp) sp->defrangulate(); // tell the Thing to do something else cout << "The Thing is gone!" << endl; }
也可以直接从weak_ptr构建shared_ptr,这个时间如果weak_ptr过期(通过 weak_ptr::expired() 可以查询),则抛出异常:
void do_it(weak_ptr<Thing> wp){ shared_ptr<Thing> sp(wp); // construct shared_ptr from weak_ptr // exception thrown if wp is expired, so if here, sp is good to go sp->defrangulate(); // tell the Thing to do something }
这篇关于C++ 中 shared_ptr weak_ptr的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升