Linux c++ 试验-5 double free问题

如果结构体中有string,不能使用memcpy,不然会有double free问题,可以使用std::move

#include <cstring>
#include <cstdio>
#include <iostream>
#include <iostream>
#include <tuple>
#include <memory>
struct teststdmov
{
	std::string str1;
	std::string str2;
};
int main()
{
	using namespace std;
	teststdmov t1;
	teststdmov t2;
	t1.str1="aaaa";
	t1.str2="bbbb";
	t2=std::move(t1);
	printf("%s\n",t2.str1.c_str());
	printf("%s\n",t2.str2.c_str());
}

需要注意的是std::mov只能移动std::string之类的数据,不能用于基本类型(类似copy)

#include <cstring>
#include <cstdio>
#include <iostream>
#include <iostream>
#include <tuple>
#include <memory>
struct teststdmov
{
	std::string str1;
	std::string str2;
	char str3[50];
	int a;
};
int main()
{
	using namespace std;
	teststdmov t1;
	teststdmov t2;
	t1.str1="aaaa";
	t1.str2="bbbb";
	sprintf(t1.str3,"ccc");
	t1.a=100;
	t2=std::move(t1);

	printf("t1str1:%s\n",t1.str1.c_str());
	printf("t1str2:%s\n",t1.str2.c_str());
	printf("t1str3:%s\n",t1.str3);
	printf("t1a:%d\n",t1.a);
	printf("t2str1:%s\n",t2.str1.c_str());
	printf("t2str2:%s\n",t2.str2.c_str());
	printf("t2str3:%s\n",t2.str3);

	t1.a=200;
	printf("t2a:%d\n",t2.a);
}

输出结果

t1str1:
t1str2:
t1str3:ccc
t1a:100
t2str1:aaaa
t2str2:bbbb
t2str3:ccc
t2a:100
[Finished in 3.1s]

std::mov是基于右值引用优化的

posted @ 2022-06-20 19:54  zhaogaojian  阅读(195)  评论(0编辑  收藏  举报