C++ 标准程序库 学习笔记 2012-09-25
4.2
1. auto_ptr是一种智能指针(smart pointer),帮助程序员防止“异常被抛出时发生资源泄露”
2. std::auto_ptr<ClassA> ptr(new ClassA); //智能指针的声明
3. auto_ptr所界定的是一种严格的拥有观念,因此绝对不能有一个物体同时被两个智能指针所拥有,因此严禁以同一个物体将两个智能指针初始化。
4. 对于auto_ptr可以用另个一auto_ptr做为指针的初值,但不能是普通指针:
1 std::auto_ptr<ClassA> ptr; //create an auto_ptr 2 std::auto_ptr<ClassA> ptr2(new ClassA); //create an auto_ptr 3 4 ptr = new ClassA; //ERROR 5 ptr = std::auto_ptr<ClassA>(new ClassA); //delete old object 6 //and own new 7 ptr = ptr2; //assign the auto_ptr 8 //-delete object owned by ptr2 9 //-transfers ownership form ptr2 to ptr
5. const std::auto_ptr<int> p(new int); //在此处,const并非意味着不能改变指针的值,而是意味着不能改变p所指内容的所有权。
6. 通用性的numeric_limits template,及其特化版本都放在<limits>头文件中,具体用法如下:
1 std::cout << "max(short): " << numeric_limits<short>::max() << std::endl; 2 std::cout << "max(int): " << numeric_limits<int>::max() << std::endl; 3 std::cout << "is_signed(char): " << numeric_limits<char>::is_signed << endl; 4 std::cout << "is_specialized(string): " << numeric_limits<string>::is_specialized << endl;
7. 有四个template functions,分别定义了 !=, >, <=, >= 四个比较运算子。它们都是利用运算子 == 和 < 完成的。如下:
1 namespace std { 2 namespace rel_ops { 3 template <class T> 4 inline bool operator!= (const T& x, const T& y) { 5 return !(x == y); 6 } 7 8 template <class T> 9 inline bool operator> (const T& x, const T& y) { 10 return y < x; 11 } 12 13 tempalte <class T> 14 inline bool operator<= (const T& x, const T& y) { 15 return !(y < x); 16 } 17 18 template <class T> 19 inline bool operator>= (const T& x, const T& y) { 20 return !(x < y); 21 } 22 } 23 }
因此只需定义了 == 和 < 运算子,即可通过 std::rel_ops 使用其它四个运算子。如下:
1 class A { 2 public: 3 4 int a; 5 bool operator== (const A& x) const { 6 return this->a == x.a; 7 } 8 bool operator< (const A& x) const { 9 return this->a < x.a; 10 } 11 }; 12 13 void isTure (const A& x, const A& y){ 14 using namespace std::rel_ops; 15 if (x >= y) 16 std::cout <<"True"<< std::endl; 17 else std::cout << "False" << std::endl; 18 }