日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++超詳細講解智能指針_C 語言

作者:清風自在?流水潺潺 ? 更新時間: 2022-07-29 編程語言

一、內存泄漏-永恒的話題

  • 動態申請堆空間,用完后不歸還
  • C++ 語言中沒有垃圾回收的機制
  • 指針無法控制所指堆空間的生命周期

下面看一段內存泄漏的代碼:

#include <iostream>
#include <string>
using namespace std;
class Test
{
    int i;
public:
    Test(int i)
    {
        this->i = i;
    }
    int value()
    {
        return i;
    }
    ~Test()
    {
    }
};
int main()
{
    for(int i=0; i<5; i++)
    {
        Test* p = new Test(i);        
        cout << p->value() << endl;      
    }    
    return 0;
}

輸出結果如下:

二、深度思考

  • 需要一個特殊的指針
  • 指針生命周期結束時主動釋放堆空間
  • 一片堆空間最多只能由一個指針標識
  • 杜絕指針運算和指針比較

三、智能指針分析

解決方案

  • 重載指針特征操作符( -> 和 * )
  • 只能通過類的成員函數重載
  • 重載函數不能使用參數
  • 只能定義一個重載函數

下面看一段智能指針的使用示例:

#include <iostream>
#include <string>
using namespace std;
class Test
{
    int i;
public:
    Test(int i)
    {
        cout << "Test(int i)" << endl;
        this->i = i;
    }
    int value()
    {
        return i;
    }
    ~Test()
    {
        cout << "~Test()" << endl;
    }
};
class Pointer
{
    Test* mp;
public:
    Pointer(Test* p = NULL)
    {
        mp = p;
    }
    Pointer(const Pointer& obj)
    {
        mp = obj.mp;
        const_cast<Pointer&>(obj).mp = NULL;
    }
    Pointer& operator = (const Pointer& obj)
    {
        if (this != &obj)
        {
            delete mp;
            mp = obj.mp;
            const_cast<Pointer&>(obj).mp = NULL;
        }
        return *this;
    }
    Test* operator -> ()
    {
        return mp;
    }
    Test& operator * ()
    {
        return *mp;
    }
    bool isNull()
    {
        return (mp == NULL);
    }
    ~Pointer()
    {
        delete mp;
    }
};
int main()
{
    Pointer p1 = new Test(0);
    cout << p1->value() << endl;
    Pointer p2 = p1;
    cout << p1.isNull() << endl;
    cout << p2->value() << endl;
    return 0;
}

輸出結果如下:

注意這兩行代碼的含義,

mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;

表明當前對象的成員指針指向初始化對象的成員指針所對應的堆空間,這就兩個智能指針對象指向了同一片堆空間,然后 const_cast<Pointer&>(obj).mp = NULL; 表明初始化對象把自己管理的堆空間交給當前對象。這就完成了前面說的“一片堆空間最多只能由一個指針標識”。

智能指針使用的軍規:只能用來指向堆空間中的對象或者變量

四、小結

  • 指針特征操作符( -> 和 * )可以被重載
  • 重載指針特征符能夠使用對象代替指針
  • 智能指針只能用于指向堆空間中的內存
  • 智能指針的意義在于最大程度的避免內存問題

原文鏈接:https://blog.csdn.net/weixin_43129713/article/details/124513911

欄目分類
最近更新