double free or corruption

源代碼

#include <iostream>
#include <cstring>
using namespace std;
class mystring
{
public:
	mystring ()
	{
		cout << "mystring構造"<<endl;
	}
	mystring (string const& m_s)
	{
		s = m_s;
	}
	~mystring (void)
	{
		cout << "mystring 析構" <<endl;
	};
	mystring & operator=(mystring & that)
	{
			s = that.s;
	}
	void print()
	{
		cout << s << endl;
	}
private:
	string s;
};
class A
{
public:
	A()
	{
		c = new mystring;
		cout << "A 構造" <<endl;	
		cout << "a:"<<c<<"\n";
	};

	A(A &that)
	{
		cout << "A拷貝構造" << endl;
		c = new mystring;
		cout<< "舊的b:"<< c << endl;
		c = that.c;
		cout << "b:"<< c << "\n" << "a:"<< that.c << endl;		
				
	}
/*	A & operator=(A &that)
	{
		*c = *that.c;
		return *this;
	}*/
	~A()
	{
		cout << "析構的地址:"<< c << "\n";
		delete c;
	}
private:
	mystring *c;
};
class B
{

};
int main ()
{
	
	A a;
	A b(a);
	return 0;
}
代碼裏的
	A(A &that)
	{
		cout << "A拷貝構造" << endl;
		c = new mystring;
		cout<< "舊的b:"<< c << endl;
		c = that.c;
		cout << "b:"<< c << "\n" << "a:"<< that.c << endl;		
				

}

c = that.c是相當於地址賦值給地址,應該改爲*c = *that.c;

還有因爲A的成員變量爲類成員指針,當A構造或拷貝構造時是不分配內存,需要new一塊內存給A的類成員存儲數據;

即mystring *c是不分配內存.NULL也是不佔內存,即mystring *c = NULL;也是不佔空間的,需要new一塊內存給它存儲.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章