zoukankan      html  css  js  c++  java
  • 智能指针类模板——创建智能指针类模板

    #ifndef _SMARTPOINTER_H_
    #define _SMARTPOINTER_H_
    
    template
    < typename T >
    class SmartPointer
    {
        T* mp;
    public:
        SmartPointer(T* p = NULL)
        {
            mp = p;
        }
    
        SmartPointer(const SmartPointer<T>& obj)
        {
            mp = obj.mp;
            const_cast<SmartPointer<T>&>(obj).mp = NULL;
        }
    
        SmartPointer<T>& operator = (const SmartPointer<T>& obj)
        {
            if( this != &obj )
            {
                delete mp;
                mp = obj.mp;
                const_cast<SmartPointer<T>&>(obj).mp = NULL;
            }
    
            return *this;
        }
    
        T* operator -> ()
        {
            return mp;
        }
    
        T& operator * ()
        {
            return *mp;
        }
    
        bool isNull()
        {
            return (mp == NULL);
        }
    
        T* get()
        {
            return mp;
        }
    
        ~SmartPointer()
        {
            delete mp;
        }
    };
    
    #endif
    #include <iostream>
    #include <string>
    #include "SmartPointer.h"
    
    using namespace std;
    
    class Test
    {
        string m_name;
    public:
        Test(const char* name)
        {
            cout << "Hello, " << name << "." << endl;
    
            m_name = name;
        }
    
        void print()
        {
            cout << "I'm " << m_name << "." << endl;
        }
    
        ~Test()
        {
            cout << "Goodbye, " << m_name << "." << endl;
        }
    };
    
    int main()
    {
        SmartPointer<Test> pt(new Test("hello world"));
    
        cout << "pt = " << pt.get() << endl;
    
        pt->print();
    
        cout << endl;
    
        SmartPointer<Test> pt1(pt);
    
        cout << "pt = " << pt.get() << endl;
        cout << "pt1 = " << pt1.get() << endl;
    
        pt1->print();
    
        return 0;
    }

    小结:
    智能指针是C++中自动内存管理的主要手段
    智能指针在各种平台上都有不同的表现形式
    智能指针能够尽可能的避开内存相关的问题
    STL和Qt中都提供了对智能指针的支持

  • 相关阅读:
    python爬取代理IP地址
    神经网络训练的过程
    机器学习中用到的数学概念
    Navicat连接Mysql错误代码1251
    mysql安装
    mysql运行找不到MSVCP140.dll
    tomcat 日志乱码
    扁平化 Flat
    常见的WEB安全及防护
    CentOS ceph 集群搭建(单节点)
  • 原文地址:https://www.cnblogs.com/-glb/p/12008058.html
Copyright © 2011-2022 走看看