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一块内存给它存储.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值