shared_from_this()
的主要用途是安全地创建 std::shared_ptr
实例来管理当前对象的生命周期,确保对象在异步任务或新线程中不会在使用过程中被销毁。示例如下:
示例代码:
#include <iostream>
#include <memory>
#include <thread>
#include <chrono>class AsyncWorker : public std::enable_shared_from_this<AsyncWorker> {
public:AsyncWorker(const std::string& name) : name(name) {std::cout << "AsyncWorker created: " << name << std::endl;}~AsyncWorker() {std::cout << "AsyncWorker destroyed: " << name << std::endl;}void startAsyncTask() {// Capture shared pointer to ensure the object stays alive during task executionstd::shared_ptr<AsyncWorker> self = shared_from_this();std::thread([self]() {std::cout << "Async task started for: " << self->name << std::endl;std::this_thread::sleep_for(std::chrono::seconds(2)); // Simulate some workstd::cout << "Async task completed for: " << self->name << std::endl;}).detach(); // Detach the thread to allow it to run independently}private:std::string name;
};int main() {std::shared_ptr<AsyncWorker> worker = std::make_shared<AsyncWorker>("Task1");worker->startAsyncTask();// Simulate some work in main threadstd::this_thread::sleep_for(std::chrono::seconds(1));std::cout << "Main thread exiting..." << std::endl;// The async task should complete before the program exitsstd::this_thread::sleep_for(std::chrono::seconds(3));return 0;
}
代码说明:
- 类继承:
AsyncWorker
类继承了std::enable_shared_from_this<AsyncWorker>
,这使得可以在类的成员函数中使用shared_from_this()
来获取一个指向当前对象的std::shared_ptr
。 - 生命周期管理:当
startAsyncTask
被调用时,shared_from_this()
创建了一个新的std::shared_ptr
,从而确保AsyncWorker
对象在异步任务完成之前不会被销毁。 - 异步任务:一个新的线程被创建,执行异步任务。在此任务中,捕获的
std::shared_ptr
确保AsyncWorker
对象的生命周期被正确管理。 - 线程管理:使用
std::thread::detach()
使线程独立运行。任务完成时,std::shared_ptr
会自动销毁。
运行结果示例:
AsyncWorker created: Task1
Async task started for: Task1
Main thread exiting...
Async task completed for: Task1
AsyncWorker destroyed: Task1
说明:
- 当主线程在 1 秒后结束时,异步任务仍在运行,但由于使用了
shared_from_this()
,AsyncWorker
对象在任务完成之前不会被销毁。 - 如果没有使用
shared_from_this()
并只是传递裸指针或常规this
指针到异步任务中,可能会引发未定义行为,因为对象可能会在异步操作期间被销毁。