当需要在类内部安全获取指向当前对象的std::shared_ptr时应使用std::enable_shared_from_this,因为直接使用std::shared_ptr<t>(this)会创建独立的引用计数导致双重释放;正确做法是让类继承std::enable_shared_from_this<t>并通过std::make_shared创建对象后调用shared_from_this(),从而确保所有返回的shared_ptr共享同一控制块,适用于回调、自引用等场景,且不可在构造函数中或未被shared_ptr管理时调用,否则会抛出异常或导致未定义行为。

当你需要在类的内部安全地获取指向当前对象的
std::shared_ptr
enable_shared_from_this
直接使用
std::make_shared<T>(this)
std::shared_ptr<T>(this)
shared_ptr
enable_shared_from_this
shared_ptr
shared_ptr
常见场景包括:
this
shared_ptr
要使用
enable_shared_from_this
std::enable_shared_from_this<T>
std::shared_ptr
shared_from_this()
shared_ptr
#include <memory>
#include <iostream>
struct MyClass : std::enable_shared_from_this<MyClass> {
void do_something() {
// 安全地获取指向自身的 shared_ptr
auto self = shared_from_this();
some_other_function(self);
}
void some_other_function(std::shared_ptr<MyClass> ptr) {
std::cout << "Called with shared_ptr\n";
}
};
int main() {
auto obj = std::make_shared<MyClass>(); // 必须用 shared_ptr 创建
obj->do_something(); // 此时 shared_from_this() 才能安全调用
}new
shared_from_this()
std::bad_weak_ptr
shared_from_this()
shared_ptr
shared_ptr
shared_from_this()
shared_ptr
MyClass* p = new MyClass; std::shared_ptr<MyClass> ptr1(p); std::shared_ptr<MyClass> ptr2(p); // 危险!两个独立的 shared_ptr 管理同一对象
这样会造成两个独立的控制块,引用计数互不相干,析构时会崩溃。
而
enable_shared_from_this
weak_ptr
shared_ptr
shared_from_this()
基本上就这些。只要记住:想在类内部返回 this
shared_ptr
shared_ptr
enable_shared_from_this
以上就是enable_shared_from_this何时使用 获取this的shared_ptr方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号