From a779779c223b1eae2bd59c7b6c8196bc4c7f7e8a Mon Sep 17 00:00:00 2001 From: Awin Huang Date: Mon, 6 Jun 2022 10:54:20 +0800 Subject: [PATCH] vault backup: 2022-06-06 10:54: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 | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/02. PARA/03. Resources(資源)/C++17/智慧指標.md b/02. PARA/03. Resources(資源)/C++17/智慧指標.md index 679c32b..705cb71 100644 --- a/02. PARA/03. Resources(資源)/C++17/智慧指標.md +++ b/02. PARA/03. Resources(資源)/C++17/智慧指標.md @@ -26,5 +26,28 @@ auto bigBuf = std::make_unique(bufferSize); ```cpp bigBuf.reset(std::make_unique(bufferSizeLarger)); ``` +這時候舊指標會自動delete,然後指向新的指標(如果記憶體分配有成功的話),或者指向nullptr(記憶體分配失敗)。 +如果單純想要釋放指標,那就單純的reset就好。 +```cpp +bigBuf.reset(); // Now I'm nullptr +``` + +如果要分配陣列的話: +```cpp +auto intArray = std::make_unique(1024); +``` + +使用方式也是一樣的: +```cpp +intArray[5] = 555; +``` + +不過對於陣列的操作現在更建議使用std::array。 + +如果有什麼特殊原因讓你決定不再讓unique_ptr蘭幫你管理指標,可以用`release`來讓出指標: +```cpp +auto intArray = std::make_unique(1024); +int* intArrayRaw = +``` ## shared_ptr \ No newline at end of file