經常有這樣的需求,在一個類裏一些成員變量需要動態地分配內存,以前是把這個成員聲明爲指針,然後在構造函數裏指定爲NULL類型,然後在析構函數裏判斷這個指針是否分配了內存,如果分配了就進行刪除。這種方式需要人工來做,工作量有點大,能否有更加高效的,能否有偷賴的方式呢?這是有的,如下的例子:
#include <memory>
class widget
{
private:
std::unique_ptr<int> data;
public:
widget(const int size) { data = std::make_unique<int>(size); }
void do_something() {}
};
void functionUsingWidget() {
widget w(1000000); // lifetime automatically tied to enclosing scope
// constructs w, including the w.data gadget member
// ...
w.do_something();
// ...
} // automatic destruction and deallocation for w and w.data
在這裏自動地分配1000000個int,當w對象不要時,就自動刪除了。是利益於使用std::unique_ptr,從這裏就可以學習到這個智能指針的使用了,它主要用來私有的數據成員。