std::move

P11

这是C11一个相当重要的特性,搬迁语义

一个应用的地方就是unique_ptr p2 = move(p2);

不能直接将一个右值引用绑定到左值上,但是我们可以利用std::move来获取一个绑定到左值的右值引用。 

move语义,即移动语义,可以将资源(堆、系统对象等)通过浅拷贝的方式从一个对象移动到另一个对象,这样能减少不必要的临时对象的创建、拷贝、销毁,可以大幅度的提升程序的性能,消除临时对象维护对性能的影响。

在设计和实现类的时候,对于需要动态申请大量资源的类,应该设计右值引用的拷贝构造函数和赋值函数,以提高应用程序的效率。

在C++中,几乎有所的容器都实现了move语义,方便我们实现性能优化,但对于一些基本类型,比如int和char[10]数组等,使用move,仍然会产生拷贝,因为没有实现对应的移动构造函数。

例子:

 1 #include <iostream>
 2 #include <utility>
 3 #include <vector>
 4 #include <string>
 5 int main()
 6 {
 7     std::string str = "Hello";
 8     std::vector<std::string> v;
 9  
10     // uses the push_back(const T&) overload, which means 
11     // we'll incur the cost of copying str
12     v.push_back(str);
13     std::cout << "After copy, str is "" << str << ""
";
14  
15     // uses the rvalue reference push_back(T&&) overload, 
16     // which means no strings will copied; instead, the contents
17     // of str will be moved into the vector.  This is less
18     // expensive, but also means str might now be empty.
19     v.push_back(std::move(str));
20     std::cout << "After move, str is "" << str << ""
";
21  
22     std::cout << "The contents of the vector are "" << v[0]
23                                          << "", "" << v[1] << ""
";
24 }

Output:

After copy, str is "Hello"
After move, str is ""
The contents of the vector are "Hello", "Hello"

move之后,str对象里面的内容被"移动"到新的对象中并插入到数组之中了,同时str被清空了。这样一来省去了对象拷贝的过程。所以说在str对象不再使用的情况下,这种做法的效率更高一些!

原文地址:https://www.cnblogs.com/raichen/p/5701318.html