diff --git a/content/posts/2019/[C++17筆記] 智慧指標:unique_ptr & shared_ptr/index.md b/content/posts/2019/[C++ 筆記] 智慧指標:unique_ptr & shared_ptr/index.md similarity index 87% rename from content/posts/2019/[C++17筆記] 智慧指標:unique_ptr & shared_ptr/index.md rename to content/posts/2019/[C++ 筆記] 智慧指標:unique_ptr & shared_ptr/index.md index a820abb..2ea7f07 100644 --- a/content/posts/2019/[C++17筆記] 智慧指標:unique_ptr & shared_ptr/index.md +++ b/content/posts/2019/[C++ 筆記] 智慧指標:unique_ptr & shared_ptr/index.md @@ -1,17 +1,17 @@ --- -slug: "[C++17 筆記] 智慧指標:unique_ptr & shared_ptr" -title: "[C++17 筆記] 智慧指標:unique_ptr & shared_ptr" +slug: "[C++ 筆記] 智慧指標:unique_ptr & shared_ptr" +title: "[C++ 筆記] 智慧指標:unique_ptr & shared_ptr" description: toc: true authors: - awin tags: - - c++17 + - c++ - memory categories: - Programming series: - - C++17 筆記 + - C++ 筆記 date: 2019-12-01T00:00:00 lastmod: 2019-12-01T00:00:00 featuredVideo: @@ -40,15 +40,22 @@ auto bigBuf = std::make_unique(bufferSize); // bigBuf will be released when exiting scope ``` -我們統一用[`std::make_unique<>`](https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique)這個template function來建立 `unique_ptr` ,角括號 `<>` 裡面要帶入你要建立的型別,後面的括號 `()` 就是型別的constructor,使用起來跟 `new` 是一樣的。 -因為 `std::make_unique<>` 裡面已經有表明型別了,所以變數就用 `auto` 就可以了,不用再寫一次型別。 +我們統一用[`std::make_unique<>`](https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique)這個template function來建立 `unique_ptr` ,角括號 `<>` 裡面要帶入你要建立的型別,後面的括號 `()` 就是型別的constructor,使用起來跟 `new` 是一樣的。 +因為 `std::make_unique<>` 裡面已經有表明型別了,所以變數就用 `auto` 就可以了,不用再寫一次型別。 -一旦 `unique_ptr` 建立之後,使用起來就跟一般指標沒有兩樣,都是用 `->` 來操作:`bigBuf->setXXX()` or `bigBuf->getXXX()`。 -但是別忘記 `unique_ptr` 本身還是一個local variable,所以我們可以用 `.` 來操作 `unique_ptr` ,例如我們可以用 `.reset()` 重新配一個指標: +一旦 `unique_ptr` 建立之後,使用起來就跟一般指標沒有兩樣,都是用 `->` 來操作,例如: ```cpp -bigBuf.reset(std::make_unique(bufferSizeLarger)); +bigBuf->setXXX(); +bigBuf->getXXX(); ``` -這時候舊指標會自動delete,然後指向新的指標(如果記憶體分配有成功的話),或者指向 `nullptr` (記憶體分配失敗)。 + +但是別忘記 `unique_ptr` 本身還是一個local variable,所以我們可以用 `.` 來操作 `unique_ptr` ,例如我們可以用 `.reset()` 重新配一個指標: +```cpp +BigBuffer* pBuffer = new BigBuffer(); +bigBuf.reset(pBuffer); +``` +這時候舊指標會自動delete,如果記憶體分配有成功的話,bigBuf會接管剛剛new出來的指標,或者變成 `nullptr` (記憶體分配失敗)。 + 如果單純想要釋放指標,那就單純的呼叫 `reset()` 就好。 ```cpp bigBuf.reset(); // Now I'm nullptr @@ -64,7 +71,7 @@ auto intArray = std::make_unique(1024); intArray[5] = 555; ``` -不過對於陣列的操作更建議使用 `std::array` 。 +不過對於陣列的操作更建議使用 `std::array` 。 如果有什麼特殊原因讓你決定不再讓 `unique_ptr` 來幫你管理指標,可以用 `release()` 來讓出指標: ```cpp