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 @   zhaogaojian  阅读(202)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2019-06-20 AntDesign vue学习笔记(一)初始化项目
2018-06-20 asp.net网页注释
点击右上角即可分享
微信分享提示