1. 程式人生 > >《Boost C++ Application Development Cookbook》筆記(持續更新)

《Boost C++ Application Development Cookbook》筆記(持續更新)

小試牛刀

  • 可用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;
}