• 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是基于右值引用优化的

  • 相关阅读:
    Win10开启自带虚拟机
    C# NPOI Word 内容读写
    纯自绘实现的winform下卡片列表
    一个宽带问题
    windows两个命令
    Windows IP 安全策略
    vue自学入门-9 @click后直接跟alert报错
    企业微信创建自建应用-2(手机端)
    企业微信创建自建应用-1(管理端)
    Ngnix实践
  • 原文地址:https://www.cnblogs.com/zhaogaojian/p/16394536.html
Copyright © 2020-2023  润新知