C++ string 使用的注意:memcpy

//----------------------------------------------------

//AUTHOR: lanyang123456

//DATE: 2014-10-30

//---------------------------------------------------



/*
str5.cpp

$ g++ -o test str5.cpp

OS Ubuntu
*/

#include 
#include 

#include 
#include 

using namespace std;

int main()
{
	string t1("123456789");
	string t2;
	
	cout<<"t1 string:"<

$ ./test
t1 string:123456789
t1 string:123456789
sizeof t1 = 4
t1.capacity = 9
t1.max_size = 1073741820
t1.size = 9
t1.length = 9
t2 string:123456789
t2 string:123456789
sizeof t2 = 4
t2.capacity = 9
t2.max_size = 1073741820
t2.size = 9
t2.length = 9
*** Error in `./test': double free or corruption (fasttop): 0x08120008 ***
Aborted (core dumped)
 
问题所在,对象不能是memcpy简单拷贝,t2 拷贝后,其指针指向所存放的字符串,该字符串所存放地址与t1中是相同的。程序结束的时候,t1,t2分别析构,由于t1和t2指向同一字符串内存,于是该内存释放两次,于是dump。
所以,对象的赋值要经过拷贝构造函数定义。


你可能感兴趣的:(Linux,C/C++)