牛骨文教育服务平台(让学习变的简单)
博文笔记

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

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

答案:是。

验证程序

[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]# 


声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。