【问题标题】:async_wait() in boost::asio fires immediately when io_service.run() is after try-catchboost::asio 中的 async_wait() 在 io_service.run() 在 try-catch 之后立即触发
【发布时间】:2016-01-21 13:01:49
【问题描述】:

我修改了 boost::asio 的 Timer.4 示例,并使用第二个参数间隔调用打印机类,如果间隔小于一则抛出。

当 io.run() 在 try-catch 中时,定时器会在指定时间后触发。

boost::asio::io_service io;

try {
    Printer p { io, 2 };
    p.print();
    io.run();
} catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
}

但是当我将它移到下方时,try-catch 会立即触发。

try {
    Printer p { io, 2 };
    p.print();
} catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
}

io.run();

可能有一个合乎逻辑的解释,它在 try-catch 之外立即触发。有人可以解释一下吗?

【问题讨论】:

    标签: c++ boost try-catch boost-asio


    【解决方案1】:

    这是因为当您离开 try-catch 范围时,p 正在破坏。 C++ 具有 RAII 编程技术。阅读更多关于这个http://en.cppreference.com/w/cpp/language/raii

    下面的例子应该可以工作:

    Printer p { io, 2 };
    try {
        p.print();
    } catch (std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
    
    io.run();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 2010-12-19
      • 2018-08-25
      相关资源
      最近更新 更多