std::move的使用
std::move
简介
#include //使用的头文件
std::move将对象的所有权从一个对象转移到另外一个对象;
std::string str1 = "string_1";
std::string str2 = std::move(str1);
系统中的块内存用str1来命名,这块内存存储的内容为“string_1”;str2 = std::move(str1),内存本身不会发生任何改变,改变的只是表示这块内存的名称,这块内存的所有权从str1转移到str2;
#include
#include
#include int main()
{std::string str1 = "string_1";std::string str2 = std::move(str1);std::cout<<"str1 is: "<<str1<<std::endl;std::cout<<"str2 is: "<<str2<<std::endl;str1 = "move test";std::cout<<"str1 is: "<<str1<<std::endl;std::cout<<"str2 is: "<<str2<<std::endl; return 0;
}
运行结果:
str1 is:
str2 is: string_1
str1 is: move test
str2 is: string_1
使用场景
可用
如果在函数中生成了string str1,并且需要将其保存到std::vector< std::string > 中,则可以使用std::move
std::vector<std::string> strVec;strVec.push_back(std::move(str1));strVec.push_back(std::move(str2));std::cout<<"str1 is: "<<str1<<std::endl;std::cout<<"str2 is: "<<str2<<std::endl;for(auto au : strVec){std::cout<<"value is: "<<au<<std::endl;}
输出结果:
str1 is:
str2 is:
value is: move test
value is: string_1
慎用
在不同的组件或者模块之间交互时慎用,尤其是交互接口的参数是指针;
void fun1(std::string& str)
{std::string s1 = std::move(str);std::cout<<"s1 is: "<<s1<<std::endl;
}
void fun2()
{std::string s2 = "function test";std::cout<<"s2 is:"<<s2<<std::endl;fun1(s2);std::cout<<"s2 is:"<<s2<<std::endl;
}
输出结果:
s2 is:function test
s1 is: function test
s2 is:
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
