cc40a_demo_Cpp_智能指针c++_txwtech

//40_21days_Cpp_智能指针c++_cc40a_demo.cpp_txwtech

//智能指针、auto_ptr类
//*常规指针-容易产生内存泄漏,内存被占满,程序就死机,或者系统死机
//*智能指针
//-》自动动手设计智能指针--很难!
//-----深度复制、写时复制、引用计数、引用链接、
//->使用std::auto_ptr智能指针--用在(破坏性复制)-功能简单
//->使用Boost智能指针,学习boost库-----------------重点学习
//->使用ATL框架中的智能指针MFC,VC++中-----------------重点学习
//如CComPtr,CComQIPtr等等。。。

 1 //40_21days_Cpp_智能指针c++_cc40a_demo.cpp_txwtech
 2 
 3 //智能指针、auto_ptr类
 4 //*常规指针-容易产生内存泄漏,内存被占满,程序就死机,或者系统死机
 5 //*智能指针
 6 //-》自动动手设计智能指针--很难!
 7 //-----深度复制、写时复制、引用计数、引用链接、
 8 //->使用std::auto_ptr智能指针--用在(破坏性复制)-功能简单
 9 //->使用Boost智能指针,学习boost库-----------------重点学习
10 //->使用ATL框架中的智能指针MFC,VC++中-----------------重点学习
11 //如CComPtr,CComQIPtr等等。。。
12 #include <iostream>
13 //#include <memory> //auto_ptr
14 #include "smart_point.h"
15 using namespace std;
16 class Dog
17 {
18 
19 };
20 //c++没有垃圾回收功能,所有用智能指针去解决这个问题
21 void demo2()
22 {
23     auto_ptr<double> pd(new double);//模板做的一个类,函数结束前,就不用delete
24     *pd = 28.6;
25     std::auto_ptr<Dog> pDog(new Dog()); 
26     //测试自己做的智能指针smart_point.h/示范,大概的样子,实际不能用
27     smart_pointer<Dog> spDog(new Dog());//实际不能用
28     std::cout <<"demo2: "<< *pd << std::endl;
29     
30 }
31 void demo1()
32 {
33     double d;
34     d = 25.6;
35     double *pd = new double;//堆上动态分配内存
36     *pd = 25.6;
37     std::cout << d << std::endl;
38     //if (1)
39         //throw exception();//抛出异常后,无法执行到delete pd指针
40     delete pd;
41     return;
42 }
43 
44 int main()
45 {
46     demo1();
47     demo2();
48     return 0;
49 }

#include "smart_point.h"

 1 #pragma once
 2 template <typename T>
 3 class smart_pointer
 4 {
 5     //测试自己做的智能指针smart_point.h/示范,大概的样子
 6 private:
 7     T* m_pRawPointer;
 8 public:
 9     smart_pointer(T* pData) :m_pRawPointer(pData) {}
10     //复制构造函数
11     smart_pointer(const smart_pointer & anotherSP);
12     //赋值操作符
13     smart_pointer& operator=(const smart_pointer & anotherSP);
14     //间接引用操作符
15     T& operator*() const
16     {
17         return *(m_pRawPointer);
18     }
19     T* operator->() const
20     {
21         return m_pRawPointer;
22     }
23 };
posted @ 2020-01-22 16:35  txwtech  阅读(175)  评论(0编辑  收藏  举报