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 <iostream>
#include <utility>
#include <string>

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:
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值