您的位置:首页 > 编程语言 > C语言/C++

C++标准程序库读书笔记-第四章通用工具

2014-11-30 18:13 190 查看
1.Pairs(对组)

(1)class pair可以将两个值视为一个单元。任何函数需返回两个值,也需要pair。

(2)便捷地创建pair对象可以使用make_pair函数

std::make_pair(32,'@')


等价于

std::pair(int,char)(42,'@')


2.Class auto_ptr

(1)auto_ptr是一种指针:它是”它所指向的对象“的拥有者(owner)。所以,当身为对象拥有者的auto_ptr被摧毁时,该对象也将遭到摧毁。auto_ptr要求一个对象只能有一个拥有者,严禁一物二主

(2)auto_ptr不允许你使用一般指针惯用的赋值(assign)初始化方式。你必须直接使用数值来完成初始化。

std::auto_ptr<ClassA> ptr1(new ClassA);	//OK
std::auto_ptr<ClassA> ptr2 = new ClassA; //ERROR


(3)auto_ptr拥有权转移

由于一个auto_ptr会删除其所指对象,所以这个对象绝对不能同时被其他对象“拥有”。绝对不应该出现多个auto_ptr同时拥有一个对象的情况。

auto_ptr的copy构造函数和assignment操作符将对象拥有权交出去。

copy构造函数的运用

//initialize an auto_ptr with a new object
std::auto_ptr<Class A> ptr1(new ClassA);

//copy the auto_ptr
// - transfers ownership from ptr1 to ptr2
std::auto_ptr<Class A> ptr2(ptr1)


赋值动作

//initialize an auto_ptr with a new object
std::auto_ptr<Class A> ptr1(new ClassA);
std::auto_ptr<Class A> ptr2;	//create another auto_ptr
ptr2 = ptr1;	//assign the auto_ptr
// - transfers ownership from ptr1 to ptr2


如果ptr2被赋值之前正拥有另一个对象,赋值动作发生时会调用delete,将对象删除

//initialize an auto_ptr with a new object
std::auto_ptr<Class A> ptr1(new ClassA);
//initialize another auto_ptr with a new object
std::auto_ptr<Class A> ptr2(new ClassA);
ptr2 = ptr1;	//assign the auto_ptr
// - delete object owned by ptr2
// - transfers ownership from ptr1 to ptr2


(4)起点和终点(source and sink)

拥有权的转移,使得auto_ptr产生一种特殊用法:某个函数可以利用auto_ptr将拥有权交给另一个函数。

    1.某函数是数据的终点

    2.某函数是数据的起点。当一个auto_ptr被返回时,其拥有权便被转交给调用端

std::auto_ptr<ClassA> f()
{
std::auto_ptr<ClassA> ptr(new ClassA);
...
return ptr;	//transfer ownership to calling funciton
}
void g()
{
std::auto_ptr<ClassA> p;
p = f();  //p gets ownership of the returned object
//(previously returned object of f() gets deleted)
}


(5)auto_ptr作为成员之一

3.数值极限

(1)C语言所采用的预处理器常数

      整数常数定义于<climits>和<limits.h>,浮点常数定义于<cfloat>和<float.h>

(2)C++通过模板numeric_limits提供极值(定义于<limits>)

4.辅助函数

算法程序库(定义于头文件<algorithm>)内含三个辅助函数,一个用在两值之中挑选较大者,另一个用来在两值之中挑选较小者,第三个用来交换两值。

(1)swap函数

namespace std {
template<class T>
inline void swap(T& a,T& b) {
T tmp(a);
a = b;
b = tmp;
}
};


只有当swap()所依赖的copy构造操作和assignment操作行为存在时,这个调用才有效。

(2)辅助性的“比较操作符”

有四个template functions,分别定义了 !=,>,<=,>=四个比较操作符。它们都是利用操作符==和<完成的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: