1. 程式人生 > >C++解析(20):智能指針與類型轉換函數

C++解析(20):智能指針與類型轉換函數

font 類類型 有一個 安全 ont 運行 root 工作 sign

0.目錄

1.智能指針

2.轉換構造函數

3.類型轉換函數

4.小結

1.智能指針

內存泄漏(臭名昭著的Bug):

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

我們需要什麽:

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

解決方案:

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

示例——實現智能指針:

#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(3);
    
    cout << p1->value() << endl;
    
    Pointer p2 = p1;
    
    cout << p1.isNull() << endl;
    
    cout << p2->value() << endl;
    
    return 0;
}

運行結果為:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
Test(int i)
3
1
3
~Test()

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

2.轉換構造函數

再論類型轉換:
C語言標準數據類型之間會進行隱式的類型安全轉換
C語言轉換規則如下:
技術分享圖片
(C語言編譯器支持從小類型(占用內存少)轉換到大類型(占用內存多)的隱式類型轉換,因為這樣的轉換是安全的,不會發生數據截斷或者數據丟失。)

示例——隱式類型轉換的bug:

#include <iostream>
#include <string>

using namespace std;

int main()
{   
    short s = ‘a‘;
    unsigned int ui = 1000;
    int i = -2000;
    double d = i;
    
    cout << "d = " << d << endl;
    cout << "ui = " << ui << endl;
    cout << "ui + i = " << ui + i << endl;
    
    if( (ui + i) > 0 )
    {
        cout << "Positive" << endl;
    }
    else
    {
        cout << "Negative" << endl;
    }
    
    cout << "sizeof(s + ‘b‘) = " << sizeof(s + ‘b‘) << endl;
    
    return 0;
}

運行結果為:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
d = -2000
ui = 1000
ui + i = 4294966296
Positive
sizeof(s + ‘b‘) = 4

(在大多數編譯器看來,int類型,也就是4個字節的整型數的運算是最高效的。而在sizeof(s + ‘b‘)中,是做加法運算,左操作數和右操作數都可以安全的轉換為int,那麽可以采用更高效的方式來進行運算。於是就出現bug了!)

問題:
普通類型類類型之間能否進行類型轉換
類類型之間能否進行類型轉換

再論構造函數:

  • 構造函數可以定義不同類型的參數
  • 參數滿足下列條件時稱為轉換構造函數
    1. 有且僅有一個參數
    2. 參數是基本類型
    3. 參數是其它類類型

舊式的C方式強制類型轉換:
技術分享圖片

編譯器會盡力嘗試讓源碼通過編譯(普通類型->類類型):
技術分享圖片

示例——編譯器自作聰明的行為:

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int mValue;
public:
    Test() { mValue = 0; }
    
    Test(int i) { mValue = i; }
    
    Test operator + (const Test& p)
    {
        Test ret(mValue + p.mValue);
        
        return ret;
    }
    
    int value() { return mValue; }
};

int main()
{   
    Test t;
    t = 5;    // t = Test(5);
    
    Test r;
    r = t + 10;   // r = t + Test(10);
    
    cout << r.value() << endl;
    
    return 0;
}

運行結果為:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
15

編譯器盡力嘗試的結果是隱式類型轉換

隱式類型轉換:

  • 會讓程序以意想不到的方式進行工作
  • 是工程中bug的重要來源

工程中通過explicit關鍵字杜絕編譯器的轉換嘗試
轉換構造函數被explicit修飾時只能進行顯示轉換
轉換方式:
技術分享圖片

示例——杜絕編譯器的轉換嘗試:

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int mValue;
public:
    Test() { mValue = 0; }
    
    explicit Test(int i) { mValue = i; }
    
    Test operator + (const Test& p)
    {
        Test ret(mValue + p.mValue);
        
        return ret;
    }
    
    int value() { return mValue; }
};

int main()
{   
    Test t;
    t = static_cast<Test>(5);    // t = Test(5);
    
    Test r;
    r = t + static_cast<Test>(10);   // r = t + Test(10);
    
    cout << r.value() << endl;
    
    return 0;
}

運行結果為:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
15

3.類型轉換函數

問題:
類類型是否能夠類型轉換到普通類型

類型轉換函數:

  • C++類中可以定義類型轉換函數
  • 類型轉換函數用於將類對象轉換為其它類型
  • 語法規則:

技術分享圖片

示例——只有想不到,沒有做不到:

#include <iostream>

using namespace std;

class Test
{
    int mValue;
public:
    Test(int i = 0) { mValue = i; }
    operator int() { return mValue; }
};

int main()
{
    Test t(100);
    int i = t; // ==> t.operator int()
    
    cout << "i = " << i << endl;
    
    return 0;
}

運行結果為:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
i = 100

類型轉換函數:

  • 轉換構造函數具有同等的地位
  • 使得編譯器有能力將對象轉化為其它類型
  • 編譯器能夠隱式的使用類型轉換函數

編譯器會盡力嘗試讓源碼通過編譯:
技術分享圖片

類型轉換函數 vs 轉換構造函數

  • 無法抑制隱式的類型轉換函數調用
  • 類型轉換函數可能與轉換構造函數沖突
  • 工程中以Type toType()的公有成員代替類型轉換函數

示例——能通過編譯的類型轉換函數:

#include <iostream>
#include <string>

using namespace std;

class Test;

class Value
{
public:
    Value() {}
};

class Test
{
    int mValue;
public:
    Test(int i = 0) { mValue = i; }
    int value() { return mValue; }
    operator Value()
    {
        Value ret;
        cout << "operator Value()" << endl;
        return ret;
    }
};

int main()
{   
    Test t(100);
    Value v = t; // ==> t.operator Value()
    
    return 0;
}

示例——能通過編譯的轉換構造函數:

#include <iostream>
#include <string>

using namespace std;

class Test;

class Value
{
public:
    Value() {}
    Value(Test& t) {}
};

class Test
{
    int mValue;
public:
    Test(int i = 0) { mValue = i; }
    int value() { return mValue; }
};

int main()
{   
    Test t(100);
    Value v = t; // ==> Value(t)
    
    return 0;
}

示例——沖突的類型轉換函數與轉換構造函數:

#include <iostream>
#include <string>

using namespace std;

class Test;

class Value
{
public:
    Value() {}
    Value(Test& t) {}
};

class Test
{
    int mValue;
public:
    Test(int i = 0) { mValue = i; }
    int value() { return mValue; }
    operator Value()
    {
        Value ret;
        cout << "operator Value()" << endl;
        return ret;
    }
};

int main()
{   
    Test t(100);
    Value v = t;
    
    return 0;
}

報錯信息為:

[root@bogon Desktop]# g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:32: error: conversion from ‘Test’ to ‘Value’ is ambiguous
test.cpp:21: note: candidates are: Test::operator Value()
test.cpp:12: note:                 Value::Value(Test&)

示例——使用explicit關鍵字避免沖突:

#include <iostream>
#include <string>

using namespace std;

class Test;

class Value
{
public:
    Value() {}
    explicit Value(Test& t) {}
};

class Test
{
    int mValue;
public:
    Test(int i = 0) { mValue = i; }
    int value() { return mValue; }
    operator Value()
    {
        Value ret;
        cout << "operator Value()" << endl;
        return ret;
    }
};

int main()
{   
    Test t(100);
    Value v = t;
    
    return 0;
}

4.小結

  • 指針特征操作符( -> * )可以被重載
  • 重載指針特征符能夠使用對象代替指針
  • 智能指針只能用於指向堆空間中的內存
  • 智能指針的意義在於最大程度的避免內存問題
  • 轉換構造函數只有一個參數
  • 轉換構造函數的參數類型是其它類型
  • 轉換構造函數在類型轉換時被調用
  • 隱式類型轉換是I程中bug的重要來源
  • explicit關鍵字用於杜絕隱式類型轉換
  • C++類中可以定義類型轉換函數
  • 類型轉換函數用於將類對象轉換為其它類型
  • 類型轉換函數與轉換構造函數具有同等的地位
  • 工程中以Type toType()的公有成員代替類型轉換函數

C++解析(20):智能指針與類型轉換函數