1. 程式人生 > >C++解析(20):智慧指標與型別轉換函式

C++解析(20):智慧指標與型別轉換函式

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;
}

執行結果為:

[[email protected] Desktop]# g++ test.cpp
[[email protected] 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;
}

執行結果為:

[[email protected] Desktop]# g++ test.cpp
[[email protected] 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;
}

執行結果為:

[[email protected] Desktop]# g++ test.cpp
[[email protected] 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;
}

執行結果為:

[[email protected] Desktop]# g++ test.cpp
[[email protected] 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;
}

執行結果為:

[[email protected] Desktop]# g++ test.cpp
[[email protected] 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;
}

報錯資訊為:

[[email protected] 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()的公有成員代替型別轉換函式