c++ - 带有 shared_ptr 的处理程序中的分段错误
问题描述
我正在尝试制作一个仅适用于应用程序执行中的第一个会话的代理。它SIGSEGV
试图处理第二个。
它的工作方式如下:
- 客户端连接
- 代理连接到终端服务器(每个会话的唯一连接)
- 代理向服务器发送数据,从服务器获取处理过的数据并将处理过的数据发送给客户端
- 代理断开与服务器和客户端的连接
问题是当我们启动应用程序并且第一个客户端尝试使用代理时,它工作正常(让客户端始终连接到代理,例如第一个获取其数据,断开连接,然后第二个连接)。但是当第二个尝试在此之后连接时,执行甚至无法到达函数中的和捕获handleAccept
(我在 Linux 中工作)。SIGSEGV
__atomic_add
atomicity.h
我无法理解我错误地制作处理程序,错误地使用shared_ptr
's,或两者兼而有之。
run
在创建对象后调用一次Proxy
以使其接受并处理客户端连接:
void Proxy::run() // create the very first session and keep waiting for other connections
{
auto newSession = std::make_shared<Session>(ioService_);
acceptor_.async_accept(
newSession->getClientSocket(),
[&](const boost::system::error_code &error) // handler is made according to boost documentation
{
handleAccept(newSession, error);
}
);
ioService_.run();
}
handleAccept
做几乎相同的事情,但也使会话开始在客户端和端服务器之间传输数据:
void Proxy::handleAccept(std::shared_ptr<Session> session, const boost::system::error_code &error) // handle the new connection and keep waiting other ones
{
if (!error)
{
session->connectToServer(serverEndpoint_);
session->run(); // two more shared_ptr's to session are appeared here and we just let it go (details are further)
}
auto newSession = std::make_shared<Session>(ioService_);
acceptor_.async_accept(
newSession->getClientSocket(),
[&](const boost::system::error_code &error)
{
handleAccept(newSession, error);
}
);
}
Session
包含两个Socket
对象(服务器和客户端),每个对象都有shared_ptr
它。当他们每个人都将完成所有操作或发生某些错误时,他们reset
将shared_ptr
进入会话,因此将其释放。
解决方案
为什么你在 handleAccept(...) 中通过引用来使用/捕获局部变量?:
acceptor_.async_accept(
newSession->getClientSocket(),
[&](const boost::system::error_code &error)
{
handleAccept(newSession, error);
}
);
您想使用:
acceptor_.async_accept(
newSession->getClientSocket(),
[this, newSession](const boost::system::error_code &error)
{
handleAccept(newSession, error);
}
);
lambda 将在函数完成后运行,并且在此之前局部变量 newSession 将被销毁。
推荐阅读
- ms-access - Ms Access 中的动态 sql 语句
- react-native - 如果文本为“长”,则 typeText 的排毒测试失败
- reactjs - 无法读取 Redux thunk 操作上未定义的属性“then”
- jquery - 即使从使用 dataUrl 定义的服务器资源返回响应,也不会调用 Jqgrid buildselect 函数
- javascript - AJAX POST 在 android studio webview 中不起作用
- javascript - 无法更改我的 javascript 以使其适合!- CSS和JavaScript
- angular - PhantomJS: Unexpected nSyntaxError: Unexpected token '>' in GitlabCI
- c# - 查询mongo文档数组
- .net - Visual Studio 项目安装程序、启动文件夹、文件名
- shell - 将 Perl 代码转换为 shell