std::move()函数的例子
时间: 2023-08-15 10:07:57 浏览: 48
当使用std::move()时,通常是将一个对象的所有权转移给另一个对象。以下是std::move()函数的一个示例:
```cpp
#include <iostream>
#include <vector>
// 定义一个类Foo
class Foo {
public:
Foo() { std::cout << "Default constructor" << std::endl; }
Foo(const Foo& other) { std::cout << "Copy constructor" << std::endl; }
Foo(Foo&& other) { std::cout << "Move constructor" << std::endl; }
};
int main() {
std::vector<Foo> source; // 创建一个存储Foo对象的向量
// 向source中添加两个Foo对象
source.push_back(Foo());
source.push_back(Foo());
std::vector<Foo> destination;
// 使用std::move()将source中的所有对象移动到destination中
destination = std::move(source);
return 0;
}
```
在上面的示例中,我们首先定义了一个名为Foo的类,它具有默认构造函数、拷贝构造函数和移动构造函数。然后,在main函数中,我们创建了两个存储Foo对象的向量source和destination。
接下来,我们向source中添加两个Foo对象。然后,我们使用std::move()将source中的所有对象移动到destination中。通过使用std::move(),我们将source的所有权转移给了destination,避免了不必要的拷贝操作。
在输出中,您将看到"Move constructor"被调用两次,这表明在对象移动时调用了移动构造函数。
希望这个示例能够帮助您理解std::move()函数的用法。如果您有任何进一步的问题,请随时提问。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)