61 - 智能指针类模板

---- 整理自狄泰软件唐佐林老师课程

1. 智能指针

1.1 智能指针的意义

  • 现代C++开发库中最重要的类模板之一
  • C++中自动内存管理的主要手段
  • 能够很大程度上避开内存相关的问题

1.2 STL中智能指针 auto_ptr

  • 生命周期结束时,销毁指向的内存空间
  • 不能指向堆数组,只能指向堆对象(变量)
  • 一片堆空间只属于一个智能指针对象
  • 多个智能指针对象不能指向同一片堆空间

1.3 编程实验:auto_ptr使用初探

#include 
#include 
#include 

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()
{
    auto_ptr<Test> pt(new Test("D.T.Software"));
    
    cout << "pt = " << pt.get() << endl;
    
    pt->print();
    
    cout << endl;
    
    auto_ptr<Test> pt1(pt);
    
    cout << "pt = " << pt.get() << endl;
    cout << "pt1 = " << pt1.get() << endl;
    
    pt1->print();
    
    return 0;
}

61 - 智能指针类模板_第1张图片

1.4 STL中的其它智能指针

shared_ptr:带有引用计数机制,支持多个指针对象指向同一片内存
weak_ptr:配合shared_ptr而引入的一种智能指针
unique_ptr:一个指针对象指向一片内存空间,不能拷贝构造和赋值

1.5 Qt中的智能指针

QPointer:
当其指向的对象被销毁时,它会被自动置空
析构时不会自动销毁所指向的对象
QSharedPointer:
引用计数型智能指针
可以被自由地拷贝和赋值
当引用计数为0时才删除指向的对象

1.6 编程实验:Qt中的智能指针

1.7 Qt中的其它智能指针

QWeakPointer
QScopedPointer
QScopedArrayPointer
QSharedDataPointer
QExplicitlySharedDataPointer

1.8 编程实验:创建智能指针类模板

#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

61 - 智能指针类模板_第2张图片

2. 小结

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

你可能感兴趣的:(C++深度解析教程,c++,开发语言)