简单测试std::move

来源:互联网 发布:卡来宝网络培训诈骗 编辑:程序博客网 时间:2024/05/29 11:43

std::move(t),用于指示对象 t 可以“被移动”,即允许从 t 到另一对象的有效率的资源传递。

假设将t赋值给t1,即:
t1=std::move(t);

操作完成后,t的值(内容)给了t1,t本身没有值了。

举例:

#include <iostream>#include <utility>#include <string>int main(int argc, const char * argv[]) {    std::string str1 = "Hello_1";    std::string str2;    std::string str3 = "Hello_3";    std::string str4;    // 将str1赋值给str2,    // 将带来复制 str1 的成本    str2 = str1;    std::cout << "copy str1 to str2, after copy, str2 is \"" << str2 << "\" and str1 is \"" << str1 << "\"\n\n";    // 使用std::move    // 表示不复制字符串;而是    // str3 的内容被移动到 str4    // 这个开销比较低,但也意味着 str3 现在将为空。    str4 = std::move(str3);    std::cout << "move str3 to str4, after move, str4 is \"" << str4 << "\" and str3 is \"" << str3 << "\"\n\n";    return 0;}

运行结果:

copy str1 to str2, after copy, str2 is "Hello_1" and str1 is "Hello_1"move str3 to str4, after move, str4 is "Hello_3" and str3 is ""

参考

http://zh.cppreference.com/w/cpp/utility/move