阅读背景:

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

来源:互联网 

答案:是。

验证程序

[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]# 
[root@gdc1000 z]# g++ -o test



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: