From 5dc96156934cebf2107815dd27addb97ee3cc1f9 Mon Sep 17 00:00:00 2001 From: Awin Huang Date: Mon, 6 Jun 2022 11:14:20 +0800 Subject: [PATCH] vault backup: 2022-06-06 11:14:20 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Affected files: 02. PARA/03. Resources(資源)/C++17/智慧指標.md --- .../03. Resources(資源)/C++17/智慧指標.md | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/02. PARA/03. Resources(資源)/C++17/智慧指標.md b/02. PARA/03. Resources(資源)/C++17/智慧指標.md index 32b9925..ef2fdab 100644 --- a/02. PARA/03. Resources(資源)/C++17/智慧指標.md +++ b/02. PARA/03. Resources(資源)/C++17/智慧指標.md @@ -5,9 +5,7 @@ unique_ptr與shared_ptr都是智慧指標,箱對於原本的raw pointer,智 原本分配記憶體的方法,假設我們有一個class叫`BigBuffer`: ```cpp BigBuffer* bigBuf = new BigBuffer(bufferSize); - // Use buffer here - delete bigBuf; ``` @@ -18,7 +16,7 @@ auto bigBuf = std::make_unique(bufferSize); // bigBuf will be released when exiting scope ``` -我們統一用`std::make_unique<>`這個template function來建立`unique_ptr`,角括號`<>`裡面要帶入你要建立的型別,後面的括號`()`就是型別的constructor,使用起來跟new是一樣的。 +我們統一用`std::make_unique<>`這個template function來建立`unique_ptr`,角括號`<>`裡面要帶入你要建立的型別,後面的括號`()`就是型別的constructor,使用起來跟`new`是一樣的。 因為`std::make_unique<>`裡面已經有表明型別了,所以變數就用`auto`就可以了,不用再寫一次型別。 一旦`unique_ptr`建立之後,使用起來就跟一般指標沒有兩樣,都是用`->`來操作:`bigBuf->setXXX()` or `bigBuf->getXXX()`。 @@ -53,9 +51,31 @@ int* intArrayRaw = intArray.release(); // Now I don't care anymore `unique_ptr`不能被複製跟移動,所以下列的寫法都編不過: ```cpp +auto ptr1 = std::make_unique(5); std::unique_ptr ptr2(ptr1); // Error std::unique_ptr ptr2 = ptr1; // Error ``` +在Visual Studio 2017上,錯誤訊息是這樣:`error C2280: 'std::unique_ptr>::unique_ptr(const std::unique_ptr> &)': attempting to reference a deleted function`。 +其實就是`unique_ptr`的copy constructor跟assignment operator都被標記為delete了。 -## shared_ptr \ No newline at end of file +## shared_ptr +建立一個`shared_ptr`是使用`std::make_shared()`: +```cpp +auto myBuf = std::make_shared(bufferSize); +``` + +但是`shared_ptr`可以被複製與移動,這是跟`unique_ptr`的差別: +```cpp +auto myBuf = std::make_shared(bufferSize); + +std::shared_ptr bufCopy = myBuf; +``` + +現在bufCopy跟myBuf都指向同一個指標,他們都可以操作這個指標: +```cpp +myBuf->setZero(startAddr, endAddr); +bufCopy->setOne(startAddr, endAddr); +``` + +`shared_ptr`內部有一個參考記數(reference cou) \ No newline at end of file