《Boost C++ Application Development Cookbook》笔记(持续更新)

版权声明:本文为博主原创文章,未经博主允许不得转载。如需转载,请私信博主。 https://blog.csdn.net/TurboIan/article/details/79648290

小试牛刀

  • 可用boost::optianal来作为函数返回值的标识,函数返回值用来表示函数是否执行成功,但如果执行成功但没有正确的结果,这种情况则可以借助boost::optianal来实现

  • boost::array 函数返回数组可以用array,不用担心数据越界等问题。

转换

  • 转换字符串到数字
//boost库(效率最高)
int i = boost::lexical_cast<int>("100");
//c++
std::istringstream iss("100");
int j;
iss >> j;
  • 数字转字符串
//boost库
std::string s = boost::lexical_cast<std::string>(100);
//c++
std::stringstream ss;
ss << 100;
ss >> s;
  • 为避免int转到uint发生数值超出有限范围的错误,boost提供了类型转换
try
{
int j = -100;
boost::numeric_cast<unsigned short>(j);
}
catch(const boost::numeric::positive_overflow& e)
{
...
}
catch(const boost::numeric::negative_overflow &e)
{
...
}
  • 用户定义的类型与字符串的相互转换,必须要重载<< 和 >>两个运算符
#include<iostream>
#include<boost/lexical_cast.hpp>
using namespace std;
class negative_number
{
  unsigned short number_;
public:
  negative_number(unsigned short number) : number_(number)
  {

  }
  negative_number(){}
  unsigned short value_without_sign() const
  {
    return number_;
  }
};

//重载<<
std::ostream& operator <<(std::ostream& os, const negative_number& num)
{
  os << '-' << num.value_without_sign();
  return os;
}
//重载>>
std::istream& operator >>(std::istream& is, negative_number& num)
{
  unsigned short s;
  is >> s;
  num = negative_number(s);
  return is;
}

int main(int argc, char *argv[])
{
  negative_number n = boost::lexical_cast<negative_number>("100");
  cout<<n.value_without_sign()<<endl;
  int i = boost::lexical_cast<int>(n);
  return 0;
}

资源管理

  • 保证指针所指资源在域中被销毁.当new一个指针后,若程序在异常情况下在delete这个指针前就退出程序了,那么将造成内存泄露,此时可以使用boost::scoped_ptr.其等同于const std::auto_ptr.
#include <boost/scoped_ptr.hpp>
bool foo()
{
    boost::scoped_ptr<foo_class> p(new foo_class("fc"));
    bool something_else_happened = func(p.get());
    if (something_else_happened)
    {
        return false;
    }
    ...
    return true;
}

猜你喜欢

转载自blog.csdn.net/TurboIan/article/details/79648290
今日推荐