一个C++构造函数,内存分配的例子

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
class simpleclass
{
private:
	char *m_buf;
	int m_nSize;
	int *m_count;
public:
	simpleclass(int n=1)
	{
		m_buf=new char[n];
		m_nSize=n;

		m_count=new int;
		*m_count=1;
		cout<<"count is "<<*m_count<<endl;
	};

	simpleclass(const simpleclass &s)
	{
		m_nSize=s.m_nSize;
		m_buf=s.m_buf;
		m_count=s.m_count;

		(*m_count)++;

		cout<<"count is "<<*m_count<<endl;
	};
	~simpleclass()
	{
		(*m_count)--;
		cout<<"count is "<<*m_count<<endl;
		if(*m_count==0)
		{
			//cout <<m_nSize<<"is deleted at "<<m_buf<<endl;
			printf("%d is deleted at %xd\n",m_nSize,m_buf);
			delete[] m_buf;
			delete m_count;
		}
	};
	char *Getbuf()
	{
		return m_buf;
	};
	simpleclass& operator = (const simpleclass&s)
	{
		if(m_buf==s.m_buf)
		{
			return *this;
		}
		(*m_count)--;
		if(*m_count==0)
		{
			m_nSize=s.m_nSize;
			m_buf=s.m_buf;
			m_count=s.m_count;
			(*m_count)++;
		}
	};
};


void foo()
{
	simpleclass a;
	char *p=a.Getbuf();

	strcpy(p,"hello");
	cout <<p<<endl;

	simpleclass b=a;
	simpleclass c(20);
	c=a;//因为你在C申请的内存没有释放,所以出现内存泄漏
	cout<<"b="<<b.Getbuf()<<endl;
	printf("b=%s,c=%s\n",b.Getbuf(),c.Getbuf());
}

int main()
{
	foo();
	printf("exit main()……\n");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值