vault backup: 2025-03-04 11:12:06

This commit is contained in:
2025-03-04 11:12:06 +08:00
parent fd1b61cd3b
commit d1e51bfd2f
144 changed files with 0 additions and 0 deletions

View File

@@ -1,70 +0,0 @@
---
tags: cpp14
aliases:
date: 2025-02-10
time: 17:35:40
description:
---
move operator可以讓[[rvalue]]被參考從而進一部的消除複製的成本。例如以下的function會回傳一個很大的陣列
```cpp
vector<int> generateBigArray() {
const int size = 1000000;
vector<int> array;
for (int i = 0; i < size; i++) {
array[i] = i;
}
return array;
}
```
當我們呼叫這個function並把結果回傳到一個變數的時候每一次這個大陣列都會被複製一次
```cpp
vector<int> atemp = generateBigArray(); // 複製1000000個int
```
如果使用[[rvalue]] reference就可以避開這些複製
```cpp
vector<int>&& atemp = generateBigArray(); // 已經建立好的array會直接「移動」到atemp省下了複製的步驟
```
## move contructor
move contructor跟copy constructor很類似只是參數由`&`改成了`&&`
例:
```cpp
template <typename T>
inline Array<T>::Array(const Array&& moved) :
size{moved.size},
elements{moved.elements}
{
moved.elements = nullptr;
}
```
## move assignment operator
```cpp
template <typename T>
Array<T>& Array<T>::operator=(const Array&& rhs)
{
if (this != &rhs) {
delete [] elements;
elements = rhs.elements;
size = rhs.size;
rhs.elements = nullptr;
}
return *this;
}
```
## 明確的「移動」
如果有一個現存的「大東西」,可以使用`std::move`來把它「移」到別的地方,進而避開了複製的行為。例:
```cpp
std::vector<std::string> my_dictionary(10000000);
std::vector<std::string> dictionary2 = std::move(my_dictionary);
```
`std::move`之後my_dictionary的size會變成0。
# 參考來源