C++ 中的智能指针

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:管理数组,共享所有权。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值