Boost库使用总结

本文总结了Boost库中的重要组件,包括智能指针(auto_ptr、shared_ptr、weak_ptr、scoped_ptr)的用法,boost::static_visitor用于实现visitor模式,boost statechart的状态机库,boost thread的线程管理,boost::system_time时间处理,boost::intrusive::list的侵入式指针优势,Boost::random的随机数生成,以及Boost::PropertyTree在操作ini配置文件中的应用。此外,还介绍了Boost::optional和BOOST_FOREACH的使用。
摘要由CSDN通过智能技术生成

auto_ptrshared_ptrweak_ptrscoped_ptr用法小结

智能指针,与引用计数相关

auto_ptr: 主要为异常安全设计的,在程序正常退出或者异常终止,会调用类的析构函数,释放资源。

复制\赋值是损坏性的操作,所以不能绑定到数组或者变量指针,也不能将auto_ptr对象存储在容器中。 

auto_ptr<int> a(new int(10));
auto_ptr<int> b;
b.reset(new int(5));
a = b;

//先解除a绑定的对象

//将a指向b

//b最后为未绑定状态

if (a.get()) //来判断是否初始化auto_ptr实例

 

shared_ptr:

构造函数

std::shared_ptr<int>p5 (new int, [](int* p){ delete p;}, std::allocator<int>());

 

可以指定deleter

boost::static_visitor

visitor设计模式

不同的操作,使用同一接口访问、调用

visitor模式实现了不改变类本身,却改变类的行为的功能

想要分别处理各种不同类型的数据, Boost.Variant 为我们提供了一个名为 boost::apply_visitor() 的函数。

#include<boost/variant.hpp>
#include<boost/any.hpp>
#include<vector>
#include<string>
#include<iostream>
 
std::vector<boost::any>vector;
 
structoutput :
  public boost::static_visitor<>
{
  void operator()(double &d) const
  {
    vector.push_back(d);
  }
 
  void operator()(char &c) const
  {
    vector.push_back(c);
  }
 
  void operator()(std::string &s) const
  {
    vector.push_back(s);
  }
};
 
intmain()
{
  boost::variant<double, char,std::strin
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值