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



Request将自己添加到类EventLoop中。shared_ptrloop不是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();

相关内容

  • 没有找到相关文章

最新更新