1:array库
库 array 在 boost/array.hpp 中定义了一个模板类 boost::array 。 通过使用这个类,可以创建一个跟 C++ 里传统的数组有着相同属性的容器。
template<typename T, std::size_t N>
class array{...}
例:
#include <stdio.h>
#include <boost/array.hpp>
int main()
{
// 定义长度为3的整形数组,数据结构上等同 int a[3];
boost::array<int, 3> a;
// 数组元素赋值
a[0] = 1;
a.at(1) = 2;
*a.rbegin() = 3;
// 数组指针
int* p = a.data();
// 遍历数组
for (int i = 0; i < a.size(); i++)
{
printf("%d %d\n", a[i], p[i]);
}
return 0;
}
2:bind库
库 bind 在 boost/bind.hpp 中定义了一个模板函数 boost::bind 。 通过使用这个函数,可以将多个函数参数绑定到一起,形成一个仿函数对象,并可以选择保存成boost::function对象。
它可用来替换c++标准库中著名的 std::bind1st() 和 std::bind2nd(),简化代码。
例:
#include <boost/bind.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
void add(int i, int j)
{
std::cout << i + j << std::endl;
}
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(2);
std::for_each(v.begin(),v.end(), boost::bind(add, 10, _1));
}
//输出:11,13,12
3:smartpointers库
智能指针的原理基于一个常见的习语叫做 RAII :资源申请即初始化。
class Resource{};
class RAII{
public:
RAII(Resource* aResource):r_(aResource){} //获取资源
~RAII() {delete r_;} //释放资源
Resource* get() {return r_ ;} //访问资源
private:
Resource* r_;
};
(1)作用域指针
它独占一个动态分配的对象, 对应的类名为 boost::scoped_ptr,定义在 boost/scoped_ptr.hpp 中。作用域指针不能传递它所包含的对象的所有权到另一个作用域指针。一旦用一个地址来初始化,这个动态分配的对象将在析构阶段释放。因为一个作用域指针只是简单保存和独占一个内存地址。
#include <boost/scoped_ptr.hpp>
int main()
{
boost::scoped_ptr<int> i(new int);
*i = 1;
*i.get() = 2;
i.reset(new int);
return 0;
}
(2)作用域数组
作用域数组的析构函数使用 delete[] 操作符来释放所包含的对象。
#include <boost/scoped_array.hpp>
int main()
{
boost::scoped_array<int> i(new int[2]);
*i.get() = 1;
i[1] = 2;
i.reset(new int[3]);
}
(3)共享指针
智能指针 boost::shared_ptr 基本上类似于 boost::scoped_ptr。 关键不同之处在于 boost::shared_ptr 不一定要独占一个对象。 它可以和其他 boost::shared_ptr 类型的智能指针共享所有权。 在这种情况下,当引用对象的最后一个智能指针销毁后,对象才会被释放。
#include <vector>
#include <algorithm>
#include <boost/shared_ptr.hpp>
void print(boost::shared_ptr<int> i)
{
printf("%d\n", *i);
}
int main()
{
std::vector<boost::shared_ptr<int> > v;
{
boost::shared_ptr<int>i1(new int(1));
boost::shared_ptr<int>i2(new int(2));
v.push_back(i1);
v.push_back(i2);
}
std::for_each(v.begin(),v.end(),print);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <boost/shared_ptr.hpp>
class Test {
public:
Test(int i):_i(i)printf("construct:%d\n", _i);}
~Test() {printf("~destroyed: %d\n", _i);}
void print() {printf("Test value: %d\n", _i);}
private:
int _i;
};
int main()
{
boost::shared_ptr<Test> i1(new Test(1));
boost::shared_ptr<Test> i2(i1);
boost::shared_ptr<Test> i3(i1);
i1.reset(new Test(2));
i1->print();
i2->print();
i3->print();
return 0;
}
(4)共享数组
共享数组对应的类型是 boost::shared_array,它的定义在boost/shared_array.hpp 里。
#include <iostream>
#include <boost/shared_array.hpp>
int main()
{
boost::shared_array<int> i1(new int[2]);
boost::shared_array<int> i2(i1);
i1[0] = 1;
std::cout << i2[0] << std::endl;
return 0;
}
本文介绍了Boost库中的几个重要部分:array库提供类似C++传统数组的容器;bind库简化了函数参数绑定;smartpointers库提供了多种智能指针类型,包括作用域指针、作用域数组、共享指针及共享数组。
1万+

被折叠的 条评论
为什么被折叠?



