何时使用智能指针删除带有asio和async_accepet的套接字

When to delete socket with asio and async_accepet without using smart pointer?

本文关键字:async accepet 套接字 asio 智能 指针 删除 何时使      更新时间:2023-10-16

由于我喜欢理解代码并查看所有变量的范围和寿命,我希望能够在不使用智能指针的情况下使用 Asio 和异步调用制作服务器。然而:

  1. 我无法关闭套接字("错误的文件描述符")
  2. 我无法关闭插座(隔离错误)
  3. 我无法删除套接字(也删除套接字)

这是我的代码:

#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){
...