入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

char * 转换为std::string是内存拷贝了吗?

创建时间:2015-07-04 投稿人: 浏览次数:1097

答案:是。

验证程序

[root@gdc1000 z]# g++ -o test test.cpp
[root@gdc1000 z]# ./test
One
One
One
[root@gdc1000 z]# vi test.cpp
[root@gdc1000 z]# cat test.cpp 
#include <string>
#include <memory.h>
#include <malloc.h>
#include <iostream>
int main()
{
   char *p = (char *)malloc(8);
   memcpy(p, "One",4);
   std::string str = p;
   std::cout << str << std::endl;
   memcpy(p, "Two",4); 
   std::cout << str << std::endl;
   free(p);
   p = 0;
   std::cout << str << std::endl;
   return 1;

}
[root@gdc1000 z]# 


声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。