
weak_ptr
shared_ptr
shared_ptr
weak_ptr
weak_ptr
C++ weak_ptr
shared_ptr
shared_ptr
weak_ptr
weak_ptr
shared_ptr
要访问
weak_ptr
lock()
weak_ptr
shared_ptr
shared_ptr
lock()
shared_ptr
shared_ptr
lock()
shared_ptr
weak_ptr
lock()
weak_ptr
在我看来,
weak_ptr
shared_ptr
Parent
Child
Parent
Child
shared_ptr
Child
Parent
shared_ptr
shared_ptr
立即学习“C++免费学习笔记(深入)”;
weak_ptr
Parent
Child
shared_ptr
Child
Parent
weak_ptr
Child
Parent
Parent
Child
Parent
Parent
shared_ptr
Child
weak_ptr
weak_ptr
weak_ptr
lock()
从
weak_ptr
lock()
weak_ptr
operator*
operator->
lock()
weak_ptr::lock()
shared_ptr
lock()
shared_ptr
shared_ptr
lock()
shared_ptr
lock()
shared_ptr
lock()
shared_ptr
nullptr
因此,安全访问的范式总是这样的:
std::weak_ptr<MyClass> weakPtr = ...; // 从某个shared_ptr初始化
if (auto sharedPtr = weakPtr.lock()) {
// 对象仍然存在,可以安全地通过 sharedPtr 访问 MyClass 的成员
sharedPtr->doSomething();
// 在这个 if 块内,sharedPtr 确保了对象的存活
} else {
// 对象已经不存在了,或者说,它已经被销毁了
std::cout << "对象已失效或被销毁。" << std::endl;
}这种模式非常重要,因为它避免了经典的“use-after-free”错误。
lock()
shared_ptr
lock()
weak_ptr
在实际的项目开发中,
weak_ptr
典型应用场景:
weak_ptr
shared_ptr
weak_ptr
weak_ptr
weak_ptr
lock()
weak_ptr
lock()
shared_ptr
lock()
weak_ptr
shared_ptr
shared_ptr
weak_ptr
lock()
weak_ptr
容易踩的坑:
lock()
weak_ptr
*weakPtr
weakPtr->member
lock()
shared_ptr
lock()
shared_ptr
shared_ptr
weak_ptr
weak_ptr
weak_ptr
lock()
shared_ptr
lock()
shared_ptr
lock()
shared_ptr
shared_ptr
shared_ptr
weak_ptr
weak_ptr
weak_ptr
weak_ptr
以上就是C++weak_ptr观察对象而不增加引用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号