使用 shared_ptr 后 "terminate called after throwing an instance of 'std::bad_weak_ptr' " 是什么

what is "terminate called after throwing an instance of 'std::bad_weak_ptr' " after I use shared_ptr

class Request 将自己添加到 class EventLoop 中。 shared_ptr loop 不是 nullptr。但是,我遇到了一些问题。 代码如下:

#include <iostream>
#include <vector>
#include <memory>
using namespace std;

class Request;
typedef std::shared_ptr<Request> RequestPtr;


class EventLoop
{
public:
    EventLoop();
    ~EventLoop();
    vector<RequestPtr> relist;

    void add_request(RequestPtr re)
    {
        relist.push_back(re);
    }
};
typedef std::shared_ptr<EventLoop> EventLoopPtr;

EventLoop::EventLoop() {}
EventLoop::~EventLoop() {}


class Request: public std::enable_shared_from_this<Request>
{
public:
    Request();
    ~Request();
    EventLoopPtr loop;

    void add_inself()
    {
        loop->add_request(shared_from_this());
        cout << "Yes, success adding into it" << endl;
    }
};

Request::Request(): loop(std::make_shared<EventLoop>())
{}

Request::~Request() 
{}

int main()
{
    Request r;
    r.add_inself();

    std::cout << "END" << std::endl;
    return 0;
}

错误信息是:

terminate called after throwing an instance of 'std::bad_weak_ptr'
what():  bad_weak_ptr
Aborted

有什么解决办法吗? 非常感谢

为了使用 shared_from_this,您需要拥有该共享指针。在 main 函数中,尝试实例化的不是堆对象 Request,而是 std::shared_ptr<Request> r = std::make_shared<Request>(); r->add_inself();