标准库 智能指针( smart pointer ) 是啥玩意儿
一,为什么有智能指针???
c++程序员需要自己善后自己动态开辟的内存,一旦忘了释放,内存就泄露。
智能指针可以帮助程序员"自动释放"自己开辟的内存。
二,从哪里看出来智能了???
- int *p = new int(11);
- auto_ptr<int> pa(p);//auto_ptr已经不推荐使用
- //delete p;
上面的代码把p交给智能指针auto_ptr管理后,就不需要自己去delete p。auto_ptr会去释放p,所以体现出了"智能"。
三,哪里看起来像指针了???
- int *p = new int(11);
- my_auto_ptr<int> pa(p);                                                                
- *pa = 111;
- cout << *pa << endl;
- cout << *p << endl;
上面的代码对智能指针pa使用了,*运算符,并且通过pa改变了p的值,所以看起来像指针哦。
- class Test{
- public:
-   void fun(){
-     cout << "func()" << endl;
-   }
- };
-  
- Test* pt = new Test;
- auto_ptr<Test> pa1(pt);
- pa1->fun();
上面的代码对智能指针pa1使用了,->运算符,并且通过pa1调用了对象pt的fun()成员方法,所以看起来像指针哦。
四,智能指针到底是个啥玩意儿???
是个模板类。
五,智能指针的是怎么实现智能和指针的?
- 在模板类里重写operator* 运算符 
- 在模板类里重写operator->运算符 
- 管理指针的所有权和转移(下面的例子没有实现) 
- #include <iostream>
- #include <memory>
-  
- using namespace std;
-  
- template<typename T>
- class my_auto_ptr{
- public:
-   my_auto_ptr(T* p = nullptr):own(p!=nullptr),ptr(p){}
-   ~my_auto_ptr(){
-     if(own){
-       delete ptr;
-     }
-   }
-   T& operator*()const{
-     return *ptr;
-   }
-   T* operator->()const{
-     return ptr;
-   }
- private:
-   bool own;
-   T* ptr;
- };
- class Test{
- public:
-   void fun(){
-     cout << "func()" << endl;
-   }
- };
- int main(){
-   //test1 老版本的auto_ptr的使用,现在不推荐使用                                
-   /*                                                                            
-   int *p = new int(10);                                                         
-   auto_ptr<int> pa(p);                                                          
-   cout << *pa << endl;                                                          
-                                                                                 
-   string* ps = new string("aaa");                                               
-   auto_ptr<string> pas(ps);                                                     
-   cout << pas->size() << endl;                                                  
-   */
-  
-   //test2 自己实现auto_ptr                                                      
-   int *p = new int(11);
-   my_auto_ptr<int> pa(p);
-   //delete p;                                                                   
-   *pa = 111;
-   cout << *pa << endl;
-   cout << *p << endl;
-  
-   Test* pt = new Test;
-   my_auto_ptr<Test> pa1(pt);
-   pa1->fun();
-  
-   return 0;
- }
github完整代码