C++ Move特性.

来源:互联网 发布:windows 7经典主题 编辑:程序博客网 时间:2024/05/18 00:45

重要的话写前面:

       它实现了移动拷贝好书和移动复制函数,从而使用右值是减少了一些不必要的临时变量的生成和复制.

#include <iostream>#include <utility>#include <vector>#include <string> int main(){    std::string str = "Hello";    std::vector<std::string> v;     // uses the push_back(const T&) overload, which means     // we'll incur the cost of copying str    v.push_back(str);    std::cout << "After copy, str is \"" << str << "\"\n";     // uses the rvalue reference push_back(T&&) overload,     // which means no strings will be copied; instead, the contents    // of str will be moved into the vector.  This is less    // expensive, but also means str might now be empty.    v.push_back(std::move(str));    std::cout << "After move, str is \"" << str << "\"\n";     std::cout << "The contents of the vector are \"" << v[0]                                         << "\", \"" << v[1] << "\"\n";}

Possible output:

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

原创粉丝点击