zoukankan      html  css  js  c++  java
  • 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 };
    欢迎讨论,相互学习。 txwtech@163.com
  • 相关阅读:
    Luogu P2391 白雪皑皑 && BZOJ 2054: 疯狂的馒头 并查集
    Luogu P3391 文艺平衡树(Splay or FHQ Treap)
    [笔记] 平衡树合集(Treap,Splay,替罪羊,FHQ Treap)
    P1353_[USACO08JAN]跑步Running 我死了。。。
    Luogu P1436 棋盘分割 暴力DP
    Luogu P1131 [ZJOI2007]时态同步 树形DP
    Luogu P1282 多米诺骨牌 DP。。背包?
    Luogu P1273 有线电视网 树形DP
    Luogu P1272 重建道路 树形DP
    Luogu P1156 垃圾陷阱 DP
  • 原文地址:https://www.cnblogs.com/txwtech/p/12228888.html
Copyright © 2011-2022 走看看