#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");
}
一个C++构造函数,内存分配的例子
最新推荐文章于 2023-09-08 12:39:18 发布