37-智能指針分析
永恆的話題
內存泄漏(臭名昭著的Bug)
- 動態申請堆空間,用完後不歸還
- 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(int argc, const char* argv[]) {
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(int argc, const char* argv[]) {
Pointer p1 = new Test(0);
cout << p1->value() << endl;
Pointer p2 = p1;
cout << p1.isNull() << endl;
cout << p2->value() << endl;
return 0;
}
智能指針的使用軍規:只能用來指向堆空間中的對象或者變量。