1. auto_ptr的使用
1> 不用使用operator = ,这样会转移控制权。(下面会给出例子解释)
2> 调用release并不会释放释放对象,仅仅是归还控制权。
3> 由于operator = 的问题,不能将auto_ptr指针放进STL容器。
4> auto_ptr不能指向数组,因为auto_ptr析构调用的时候只能调用delete,不能调用 delete[]
class A
8 {
9 public:
10 int number;
11 char* cc;
12 public:
13 A(int num):number(num){cc=new char[100];cout<<"A()"<<endl;}
14 ~A(){delete[] cc;cout<<"~A()"<<endl;}
15 void say()
16 {
17 cout<<"this is the say function"<<endl;
18 cout<<"the number is "<<number<<endl;
19 cout<<"the cc is "<<cc<<endl;
20 }
21 };
22 int main()
23 {
24 A* pA=new A(10);
25 auto_ptr<A> ptr(pA);
26 if(ptr.get())//使用get()返回裸指针,判断指针是否为空
27 {
28 memcpy(ptr->cc,"dafas",sizeof("dafas"));
29 ptr->say();
30 }
31 //以上运行正常
32 //-------------------------------------
33 // auto_ptr<A> ptrX;
34 // ptrX=ptr;
35 // ptrX->say();
36 // ptr->say(); 这一句会报段核心错误,因为ptr的控制权已经交给了ptrX.所以使用 std::auto_ptr 时,绝对不能使用“operator=”操作符
37 //-------------------------------
38 //下面讲述释放内存
//---------------------
40 /* if(ptr.get())
41 {
42 A* temp=ptr.release();
43 delete temp;
44 }*/
45 //------------------
46 //或者
47 if(ptr.get())
48 {
49 ptr.reset();
50 }
51 }
2. shared_ptr共享所有权,所以智能指针能够作为参数进行传递。
3. shared_array:管理数组,共享所有权。