vault backup: 2022-06-09 14:40:26

Affected files:
.obsidian/workspace
02. PARA/03. Resources(資源)/C++17/rvalue.md
02. PARA/03. Resources(資源)/C++17/智慧指標.md
This commit is contained in:
2022-06-09 14:40:26 +08:00
parent 886122f8da
commit a7a1b5b650
3 changed files with 20 additions and 5 deletions

View File

@@ -190,7 +190,13 @@ BigBuffer constructor
BigBuffer copy operator, copy 104857600Bytes
```
還是使用 copy operator
還是使用 copy assignment operator 來複製,理由是一樣的,需要一個明確的 `std::move()` 來表示「轉移」的行動,把程式改成:
```cpp
BigBuffer b1, b2;
b2 = std::move(b1);
```
這樣就可以了。
## 參考
- [Value categories - cppreference.com](https://en.cppreference.com/w/cpp/language/value_category)

View File

@@ -60,6 +60,15 @@ std::unique_ptr<int> ptr2 = ptr1; // Error
在Visual Studio 2017上錯誤訊息是這樣`error C2280: 'std::unique_ptr<int,std::default_delete<int>>::unique_ptr(const std::unique_ptr<int,std::default_delete<int>> &)': attempting to reference a deleted function`
其實就是`unique_ptr`的copy constructor跟assignment operator都被標記為delete了。
### Move a unique_ptr
如果一定要把 unique_ptr 指定給別人可以嗎?可以的,用 `std::move()` 來轉移:
```cpp
auto ptr1 = std::make_unique<int>(5);
// do something
auto anotherPtr = std::move(ptr1);
```
ptr1原本所管理的指標會轉移給 anotherPtr
## shared_ptr
建立一個 `shared_ptr` 是使用[`std::make_shared()`](https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared)