关于析构函数的一点问题

廖根 2006-12-28 02:18:37
#include<iostream>
#include <string>
using namespace std;


class CBase
{
public:
CBase()
{
m_base=new char[5];
m_base="aaa";
record=0;
}
void setRecord(int i)
{
record=i;
}
CBase(const CBase &Cb)
{
if (&Cb==NULL)
{
return;
}
m_base=new char[5];
strcpy(m_base,Cb.m_base);
record=Cb.record;
}

CBase operator=(const CBase & Cb)
{
if (this==&Cb)
{
return *this;
}
delete[] m_base;
m_base=new char[5];
strcpy(m_base,Cb.m_base);
record=Cb.record;
return *this;
}
~CBase()
{

cout<<record;
delete []m_base;
}
private:
char *m_base;
int record;
};

void test()
{
CBase Test;
Test.setRecord(1);
CBase Test2(Test);
}
void main()
{
test();
int testin=0;
}

这个小程序为什么第2次运行到delete []m_base就会出错?要是不用cout<<record和printf,就不会出错,为什么?
...全文
111 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhousqy 2006-12-28
  • 打赏
  • 举报
回复
这个错误比较常见,用string吧
todototry 2006-12-28
  • 打赏
  • 举报
回复
m_base="aaa";
=======
m_base指向静态存储区,这块内存可读不可写
不是new出来的,你用delete释放,所以
weijiangshanwww 2006-12-28
  • 打赏
  • 举报
回复
一个new 一定要有个delete和它对应!
todototry 2006-12-28
  • 打赏
  • 举报
回复
#include <cstring>
todototry 2006-12-28
  • 打赏
  • 举报
回复
CBase()
{
m_base=new char[5];
m_base="aaa";//error
record=0;
}
=========
strcpy(m_base, "aaa");

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧