From 97d82d52e8d81d4bfa4778a2247960b91ae4d81c Mon Sep 17 00:00:00 2001 From: Awin Huang Date: Wed, 8 Jun 2022 14:52:43 +0800 Subject: [PATCH] vault backup: 2022-06-08 14:52:43 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Affected files: .obsidian/workspace 02. PARA/03. Resources(資源)/C++17/智慧指標.md --- .obsidian/workspace | 10 +++++----- 02. PARA/03. Resources(資源)/C++17/智慧指標.md | 6 ++++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/.obsidian/workspace b/.obsidian/workspace index 649845a..833bee7 100644 --- a/.obsidian/workspace +++ b/.obsidian/workspace @@ -10,7 +10,7 @@ "state": { "type": "markdown", "state": { - "file": "02. PARA/03. Resources(資源)/git/submodule.md", + "file": "02. PARA/03. Resources(資源)/C++17/智慧指標.md", "mode": "source", "source": true } @@ -23,7 +23,7 @@ "state": { "type": "outline", "state": { - "file": "02. PARA/03. Resources(資源)/git/submodule.md" + "file": "02. PARA/03. Resources(資源)/C++17/智慧指標.md" } } } @@ -81,7 +81,7 @@ "state": { "type": "backlink", "state": { - "file": "02. PARA/03. Resources(資源)/git/submodule.md", + "file": "02. PARA/03. Resources(資源)/C++17/智慧指標.md", "collapseAll": true, "extraContext": true, "sortOrder": "alphabetical", @@ -125,6 +125,7 @@ }, "active": "94f0e8a81af6c9e2", "lastOpenFiles": [ + "02. PARA/03. Resources(資源)/C++17/智慧指標.md", "02. PARA/03. Resources(資源)/git/submodule.md", "02. PARA/03. Resources(資源)/git.md", "02. PARA/03. Resources(資源)/C++17/rvalue.md", @@ -133,7 +134,6 @@ "02. PARA/01. Project(專案)/008. Sentinel.md", "02. PARA/03. Resources(資源)/FFMPEG/01. Setup.md", "02. PARA/03. Resources(資源)/FFMPEG/00. Introduction.md", - "02. PARA/03. Resources(資源)/FFMpeg.md", - "02. PARA/03. Resources(資源)/99. templates/日記.md" + "02. PARA/03. Resources(資源)/FFMpeg.md" ] } \ No newline at end of file diff --git a/02. PARA/03. Resources(資源)/C++17/智慧指標.md b/02. PARA/03. Resources(資源)/C++17/智慧指標.md index 0e8171c..2e2b28b 100644 --- a/02. PARA/03. Resources(資源)/C++17/智慧指標.md +++ b/02. PARA/03. Resources(資源)/C++17/智慧指標.md @@ -22,9 +22,11 @@ auto bigBuf = std::make_unique(bufferSize); 一旦 `unique_ptr` 建立之後,使用起來就跟一般指標沒有兩樣,都是用 `->` 來操作:`bigBuf->setXXX()` or `bigBuf->getXXX()`。 但是別忘記 `unique_ptr` 本身還是一個local variable,所以我們可以用 `.` 來操作 `unique_ptr` ,例如我們可以用 `.reset()` 重新配一個指標: ```cpp -bigBuf.reset(std::make_unique(bufferSizeLarger)); +BigBuffer* pBuffer = new BigBuffer(); +bigBuf.reset(pBuffer); ``` -這時候舊指標會自動delete,然後指向新的指標(如果記憶體分配有成功的話),或者指向 `nullptr` (記憶體分配失敗)。 +這時候舊指標會自動delete,如果記憶體分配有成功的話,bigBuf會接管剛剛new出來的指標,或者變成 `nullptr` (記憶體分配失敗)。 + 如果單純想要釋放指標,那就單純的呼叫 `reset()` 就好。 ```cpp bigBuf.reset(); // Now I'm nullptr