设为首页 加入收藏

TOP

c/c++ 标准库 智能指针( smart pointer ) 是啥玩意儿
2018-10-21 14:12:52 】 浏览:29
Tags:c/c 标准 智能 指针 smart pointer 玩意儿

标准库 智能指针( 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完整代码

c/c++ 学习互助QQ群:877684253

本人微信:xiaoshitou5854

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇牛客NOIP提高组(三)题解 下一篇HDU - 4811 - Ball (思维)

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目