现在的位置: 首页 > 综合 > 正文

STL通用工具

2013年12月02日 ⁄ 综合 ⁄ 共 906字 ⁄ 字号 评论关闭
  

Pairs(对组)
常用的一个便捷函数
namespace std{
template <typename T1,typename T2>
pair<T1,T2> make_pair(const T1& x,const T2& y)
{
return pair<T1,T2>(x,y);
}
如:
std::pair<int,char>(42,’@’);óstd::make_pair(42,’@’);
 
Class auto_ptr智能指针smart pointer
1)        auto_ptr设计的重要特点:一个对象只能有一个拥有者,严禁一物二主。
2)        创建auto_ptr时使用以下方法:
std::auto_ptr<ClassA> ptr1(new ClassA);
std::auto_ptr<ClassA> ptr2=new ClassA;//error
std::auto_ptr<ClassA> ptr3;
ptr3=new ClassA;//error
auto_ptr作为参数时初始化操作应该用冒号语法实现。
class A
{public:
A(B x):ptr(new B(x)){}
private:
std::auto_ptr<B> ptr;
};
3)        auto_ptr的拥有权的转移
l         初始化:
std::auto_ptr<ClassA> ptr1(new ClassA);
std::auto_ptr<ClassA> ptr2(ptr1);//ptr1对对象的拥有权转到ptr2ptr1内指针变为NULL
l         赋值:
std::auto_ptr<ClassA> ptr1(new ClassA);
std::auto_ptr<ClassA> ptr2(new ClassA);
ptr1=ptr2; //ptr2对对象的拥有权转到ptr1ptr2内指针变为NULLptr1不在拥有以前的对象。
l         作为函数参数
当用传值方式调用时实参auto_ptr的拥有权将转移至形参,形参在结束生命是会将拥有的东西释放掉。
当用引用参数形式传递参数时,拥有权的概念变得模糊.
4)      不存在针对Arrayauto_ptrs
 

抱歉!评论已关闭.