這篇主要要介紹smart point的使用,看完可以認識一下smart ponint的簡易用法與好處。
在軟體開發或是程式開發,只要是使用C++的語言幾乎很難不碰到point(指標)。以前課本有教指標的使用如下:
void main(void)
{
int* a = new int(6);
cout<<"a="<<*a<<endl;
delete a;
system("PAUSE");
}
第三行就是宣告一個指標a,然後在記憶體new一塊空間後把位置傳給a;
此時 a 為 0x1234 這是一個address。 *a 為 6 才是這塊 int型態的記憶體 內的值。
隨著專案越寫越大,往往會發生一個狀況....就是忘了 delete !!!!
假設我們在VC底下寫了一段忘記delete的程式....
void main(void)
{
int* a = new int(6);
cout<<"a="<<*a<<endl;
//delete a;
system("PAUSE");
}
執行一下,如果有安裝vld外掛的在書初會有以下畫面:
就會發生memory leak (記憶體破碎)。
幾年前我在五股的遊戲公司上班,這時候是使用Visual C++ 2003,該軟體用的C++標準還不到11。當時我們要處理發生memory leak問題時採用了boost 中的 smart point 。
參考:boost - smart point reference
所以,避免因為使用point造成memory leak的一個預防方法就是使用 smart point !舉個範例如下:
#include <iostream>
#include <memory>
#include "vld.h"
using namespace std;
void main(void)
{
unique_ptr a(new int(10));
cout<<"a="<<*a<<endl;
system("PAUSE");
}
上面的範例中,第9行就是宣告一個 int 型態的 smart point a 。使用 a 的方法就跟平常使用point一樣,只差在宣告不一樣。
smart point 有分為三種:
- unique point
- share point
- weak point
上面的例子就是使用 unique point 。
還有重要的一點,在使用Visual C++ 2010之前的版本是不支援 smart point 的。而Visual C++ 2010以及之後的版本都支援C++11以上,都可以使用 smart point 。
繼續努力,繼續努力!