C++ smart pointer,unique_ptr,shared_ptr

C++ smart pointer,unique_ptr,shared_ptr

smart pointer

與一般的pointer相比,smart pointer的優勢在於我們不需要顯式地呼叫delete(ptr)來釋放它所佔用的記憶體。只要smart pointer一落在可視範圍之外,smart pointer的destructor便會自動地釋放動態分配的內存。

std::unique_ptr

我們可以將std::unique_ptr看成是raw pointer的container。當我們希望一塊資源只能被一個指標所存取時,我們就可以使用std::unique_ptr

C++不允許std::unique_ptr被複製。所以如果我們想要轉移資源的擁有者,就必須借助std::move來達成。

如:

//會出錯,不能複製unique_ptr
 unique_ptr<A> ptr2 = ptr1;   
//可以成功執行
unique_ptr<A> ptr2 = move(ptr1); 

TensorRT/samples/opensource/sampleMNIST/sampleMNIST.cpp中有下面這麼一段:

template <typename T>
using SampleUniquePtr = std::unique_ptr<T, samplesCommon::InferDeleter>;

SampleUniquePtr<nvcaffeparser1::IBinaryProtoBlob>
    mMeanBlob; //! the mean blob, which we need to keep around until build is done

參照std::unique_ptr的文檔

template <
    class T,
    class Deleter
> class unique_ptr<T[], Deleter>;

可以得知samplesCommon::InferDeleter是這裡指定的deleter,在該unique_ptr被摧毀或指向別處時,deleter就會負責清理該unique_ptr所佔用的空間。

std::shared_ptr

std::shared_ptr亦是raw pointer的container。當我們希望一塊資源能被多個pointer所存取時,我們就會用到std::shared_ptr

扫描二维码关注公众号,回复: 8830165 查看本文章

C++允許多個shared_ptr指向同一塊資源。並且shared_ptr還自帶了計數功能,即,每當一個新的shared_ptr指向該資源時,reference count就會加一;而每當一個shared_ptr指向別處或是被銷毀時,reference count就會減一。

TensorRT/samples/opensource/sampleMNIST/sampleMNIST.cpp中對shared_ptr的使用:

std::shared_ptr<nvinfer1::ICudaEngine> mEngine{nullptr}; //!< The TensorRT engine used to run the network
//...
mEngine = std::shared_ptr<nvinfer1::ICudaEngine>(
        builder->buildEngineWithConfig(*network, *config), samplesCommon::InferDeleter());

以下是shared_pointer的constructor的定義,可與上面的代碼相對照:

template< class Y, class Deleter >
shared_ptr( Y* ptr, Deleter d );

參考連結

Smart Pointers in C++

auto_ptr, unique_ptr, shared_ptr and weak_ptr

std::unique_ptr

std::shared_ptr

发布了95 篇原创文章 · 获赞 9 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/keineahnung2345/article/details/104082430