C++智能指针实现

朴灿烈づ我的快乐病毒、 2024-04-17 15:36 166阅读 0赞

手动实现一个智能指针,留着以后用得到的时候再看

  1. #include <iostream>
  2. using namespace std;
  3. template <class T>
  4. class smart_ptr {
  5. public:
  6. smart_ptr (T* ptr = nullptr) : _ptr(ptr), _pCount(nullptr) {
  7. if (_ptr) {
  8. _pCount = new int (1);
  9. }
  10. cout << "smart_ptr (T* ptr)" << endl;
  11. }
  12. smart_ptr (const smart_ptr<T>& sp) : _ptr(sp._ptr), _pCount(sp._pCount){
  13. if (_ptr)
  14. (*_pCount)++;
  15. cout << "smart_ptr (smart_ptr<T>& ptr)" << endl;
  16. }
  17. ~smart_ptr () {
  18. if (_ptr && --(*_pCount) == 0) {
  19. delete _ptr; delete _pCount;
  20. _ptr = nullptr; _pCount = nullptr;
  21. }
  22. cout << "~smart_ptr ()" << endl;
  23. }
  24. smart_ptr<T>& operator= (const smart_ptr<T>& ptr) {
  25. cout << "smart_ptr<T> operator= (const smart_ptr<T>& ptr)" << endl;
  26. if (_ptr == ptr._ptr)
  27. return *this;
  28. if (_ptr && --(*_pCount) == 0) {
  29. delete _ptr; delete _pCount;
  30. _ptr = nullptr; _pCount = nullptr;
  31. }
  32. _ptr = ptr._ptr;
  33. _pCount = ptr._pCount;
  34. if (_ptr)
  35. ++(*_pCount);
  36. return *this;
  37. }
  38. int useCount () {
  39. return *_pCount;
  40. }
  41. T& operator* () {
  42. return *_ptr;
  43. }
  44. T* operator-> () {
  45. return _ptr;
  46. }
  47. T* get () {
  48. return _ptr;
  49. }
  50. private:
  51. T* _ptr;
  52. int* _pCount;
  53. };
  54. class A {
  55. public:
  56. int i;
  57. A (int n) : i(n) {}
  58. ~A () {cout << i << " destructed" << endl;}
  59. };
  60. int main (){
  61. smart_ptr<A> sp1(new A(2));
  62. smart_ptr<A> sp2(sp1);
  63. smart_ptr<A> sp3;
  64. sp3 = sp2;
  65. cout << sp1->i << "," << sp2->i << "," << sp3->i << endl;
  66. A* p = sp3.get();
  67. cout << p->i << endl;
  68. sp1 = new A(3);
  69. sp2 = new A(4);
  70. cout << sp1->i << endl;
  71. sp3 = new A(5);
  72. cout << "end" << endl;
  73. cout << (*sp3).i << " " << sp3->i << endl;
  74. return 0;
  75. }

发表评论

表情:
评论列表 (有 0 条评论,166人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C++-智能指针——简单实现分析

    > 一:为什么要有智能指针 在我们动态开辟内存时,每次new完就一定会有配套的delete来完成释放操作。可是这时候问题就来了,有时候程序未必会执行到我们释放的那一步,

    相关 C++智能指针

    1.智能指针的作用        C++程序设计中使用堆内存是非常频繁的操作,堆内存的申请和释放都由程序员自己管理。程序员自己管理堆内存可以提高了程序的效率,但是整体来说