C++11中使用shared_ptr和unique_ptr管理動態數組

在C++11中,若使用shared_ptr管理一個動態數組,則需手動制定一個刪除器。

auto sp = std::shared_ptr(new int[len], [](char *p){delete []p;});

但是這樣每次手動指定有點麻煩,經過查閱資料,發現可以使用shared_ptr爲動態數組創建一個工廠函數。

具體使用如下:

#include <iostream>
#include <memory>
#include <string.h>
using namespace std;

template <typename T>
shared_ptr<T> make_shared_array(size_t size)
{
    //default_delete是STL中的默認刪除器
    return shared_ptr<T>(new T[size], default_delete<T[]>());
}

int main()
{
    auto sp_array = make_shared_array<char>(100);
    strcpy(sp_array.get(), "hello smart pointer");
    sp_array.get()[0] = 'a';
    cout << sp_array << endl;

    //使用原始指針完成相同的功能:
    auto str_array = new char[100];
    strcpy(str_array, "hello old pointer");
    str_array[0] = 'a';
    cout << str_array << endl;
    delete [] str_array;

    return 0;
}

輸出結果爲:

aello smart pointer
aello old pointer

需要注意的是:我們常常需要對動態數組中的某一個元素進行操作,但shared_ptr沒有提供[]操作符。

不過我們可以使用 sp.get()先獲取原始指針,再對原始指針進行下標操作。

而unique_ptr對動態數組提供了支持,指定刪除器是一個可選項。也可以直接使用下標操作:

#include <iostream>
#include <memory>
#include <string.h>
using namespace std;

class mclass
{
public:
    mclass()
    {
        mem = new char[100];
        cout << "mclass constructor" << endl;
    }

    ~mclass()
    {
        delete [] mem;
        cout << "mclass deconstrucotr" << endl;
    }
public:
    char *mem;
};


int main ()
{
    std::unique_ptr<mclass[]> up (new mclass[2]);
    strcpy(up[0].mem, "hello unique_ptr");
    cout << up[0].mem << endl;
    return 0;
}

程序的輸出爲:

mclass constructor
mclass constructor
hello unique_ptr
mclass deconstrucotr
mclass deconstrucotr

PS:智能指針只能釋放它自己直接指向的內存,若上段代碼中mclass類的析構函數中忘了對mem進行釋放,依然會造成內存泄露。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章