何时使用智能指针删除带有asio和async_accepet的套接字
When to delete socket with asio and async_accepet without using smart pointer?
由于我喜欢理解代码并查看所有变量的范围和寿命,我希望能够在不使用智能指针的情况下使用 Asio 和异步调用制作服务器。然而:
- 我无法关闭套接字("错误的文件描述符")
- 我无法关闭插座(隔离错误)
- 我无法删除套接字(也删除套接字)
这是我的代码:
#include <iostream>
#include <asio.hpp>
const char * const path = "/var/local/serv.socket";
asio::local::stream_protocol::acceptor * acceptor;
asio::io_service io_service;
void handle_co(std::error_code ec){
std::cout << ec.message() << std::endl;
std::cout << "Connection !" << std::endl;
}
void loop(){
auto socket = new asio::local::stream_protocol::socket(io_service);
acceptor->async_accept(*socket, [&socket](std::error_code ec){
handle_co(ec);
std::cout<<socket->is_open() << std::endl; // 1 (true)
socket->shutdown(asio::socket_base::shutdown_both, ec);
std::cout << ec.message() << std::endl; // Bad file descriptor
socket->close(ec); // Segfault
delete socket; // Segfault
loop();
});
}
int main(int argc, char **argv) {
std::remove(path);
asio::local::stream_protocol::endpoint endpoint(path);
acceptor = new asio::local::stream_protocol::acceptor(io_service);
acceptor->open(endpoint.protocol());
acceptor->bind(endpoint);
acceptor->listen();
loop();
io_service.run();
return 0;
}
如何编辑才能工作(没有共享指针)?
问题出在 lambda [&socket]
中。通过别名捕获变量socket
您可以获得对loop()
函数堆栈中的指针的引用(在执行 lambda 时已经退出)。因此,您正在垃圾指针上调用关闭/关闭。只需通过引用删除捕获:
...
acceptor->async_accept(*socket, [socket](std::error_code ec){
...
相关文章:
- 为什么std::async使用同一个线程运行函数
- 为什么可以将左值传递给"std::async",即使它引用了右值
- 使用用户定义的参数调用future/async并调用类方法
- 使用 std::async 时死锁,将来作为成员
- 为什么我不能将引用作为 std::async 的函数参数传递
- std::async from std::async in windows xp
- Google Cloud Pubsub Async Streaming API in C++
- -fno-unwind-tables 和 -fno-async-unwind-tables 不起作用 NDK clang
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- std::async 不会立即调用
- async中没有匹配的函数(模板中未解析的类型)
- std::async 如果线程是从 DLL 创建的,则会阻止进程退出?
- 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- 可能的 std::async 实现错误 Windows
- 为什么使用线程池时嵌套调用 boost::async 会阻塞?
- C++从 std::async 函数读取命名空间中的全局变量标志
- std::async 究竟是如何执行的?
- 使用 g++8 和 c++20 的 std::async 编译问题
- 如何有效地使用 std::async 对指针数组执行操作