C++async_wait的使用(C++asio网络库相关)

async_wait的使用
async_wait传参数绑定事件调用回调函数及C++指针的黑暗面


async_wait传参数调用回调函数通过bind方式绑定,可以用lambda表达式代替。
本来调用一次print就会失效,可以通过expires_at定义下一次的失效时间来多次执行print
需要占一位参数error_code是系统参数
async_wait形参只有一个所以需要bind绑定函数和函数参数
以lambda方式效率更高

#include <iostream>
#include <boost/asio.hpp>
#include <memory>
#include <vector>
#include <boost/date_time/posix_time/posix_time.hpp>
// boost::function<>
// std::function<>

void print(const boost::system::error_code & /* e*/,
           std::shared_ptr<boost::asio::deadline_timer> t, int *count) {
  if (*count < 5) {
    std::cout << *count << std::endl;
    ++(*count);

    t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
    t->async_wait([t, count](const auto &error) { print(error, t, count); });
  }
}

void callback(const boost::system::error_code& e) {
    std::cout << "hello world\n";
}

std::shared_ptr<boost::asio::deadline_timer>
registerPrint(boost::asio::io_service &io, int *count) {
  auto t = std::make_shared<boost::asio::deadline_timer>(
      io, boost::posix_time::seconds(1));
  t->async_wait([t, count](const auto &error) { print(error, t, count); });
  return t;
}

int main() {
  boost::asio::io_service io;

    std::vector<int> v;
    for(int i = 0;i < 5; ++i) v.push_back(i);
    for (int i = 0; i < 5; ++i) {
        auto t = registerPrint(io, &v[i]);
        std::cout <<"pointer address is: " << t.get() << std::endl;
    }
  io.run();
    for(int i = 0; i < 5; ++i)
  std::cout << "Final count is " << v[i] << std::endl;

  return 0;
}

回调绑定的参数生命周期一定要足够长保证在run能够运行
如以下情况run会调用智能指针的野指针因为已经超过出了智能指针的生命周期,但不一定会出错这也是C++黑暗的一面,尽管指针已经成为了野指针但依然保留了new时的结构

在这里插入图片描述在这里插入图片描述

用vector容器打印可发现内容已经是错误的

 在这里插入图片描述

 在这里插入图片描述

 

用lambda+智能指针方式作为async_wait回调参数来延长参数生命周期及lambda本质
lambda函数本质:
遵循了类的特征,生命周期和类是一样的
如果有参数传入好比类的成员变量
传入引用就是引用本身的生命周期

在这里插入图片描述不用绑定原生指针

 在这里插入图片描述

 

可以通过在lambda绑定智能指针来延长生命周期

在这里插入图片描述在这里插入图片描述

 

但有的时候并不希望事件回调参数有如此长的生命周期希望外部来控制
还有一个弊端也改变了外部函数接口,上面例子必须要传入智能指针。。
智能指针有传染性,一个地方要用智能指针,很多地方都被迫用智能指针

 

async_wait事件绑定成员函数的方式及通过错误码判断回调参数是否失效
async_wait事件绑定成员函数的方式:
this是函数的调用者

在这里插入图片描述

以lambda方式

 在这里插入图片描述

 在类中this指针是始终有效的
有很多BUG都是调回调函数时绑定参数已经失效了
在析构的时候把所有绑定的事件的回调函数都取消掉用timer_.cancel()是没用的因为已经晚了

可以通过对错误码的判断让代码变得安全一些

在这里插入图片描述

 

————————————————
版权声明:本文为CSDN博主「昔拉天使」的原创文章
原文链接:https://blog.csdn.net/qq_39885372/article/details/104054423

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值