析构函数的调用时间

Lionheartch 2013-04-07 04:22:35
对象motto2为什么在函数中间就调用了析构函数,见注释——————

#include<iostream>
using namespace std;
class Cmessage
{
private:
char* pmessage;
public:
Cmessage(const char* text = "default message.")
{
pmessage = new char[strlen(text)+1];
strcpy(pmessage,text);
cout<<"instructor called."<<endl;
}
~Cmessage()
{
delete [] pmessage;
cout<<"destructor called."<<endl;
}
void showit()
{
cout<<pmessage<<endl;
}
Cmessage operator=(const Cmessage& amess)
{
if(this == &amess) //例如 motto == motto
return *this;
else
{
delete [] pmessage;
pmessage = new char[strlen(amess.pmessage)+1];
strcpy(this->pmessage,amess.pmessage);
return *this;
}
}
void reset()
{
char* temp = pmessage;
while(*temp)
*(temp++) = '*';
}
};
int main()
{
Cmessage motto1("fuzhigouzao.");
Cmessage motto2;
cout<<"motto2 - ";
motto2.showit();
cout<<endl;

motto2 = motto1;//为何此句结束后motto2就调用析构函数?为什么不是在return之后呢?

cout<<"motto2 - ";
motto2.showit();
cout<<endl;

motto1.reset();

cout<<"motto1 - ";
motto1.showit();
cout<<endl;

cout<<"motto2 - ";
motto2.showit();
cout<<endl;

return 0;
}



运行结果为:
Running:
instructor called.
instructor called.
motto2 - default message.

destructor called.
motto2 - 乱码 //这里不是应当为“fuzhigouzao.”吗?

motto1 - ********************************

motto2 -乱码 //同上

destructor called.
destructor called.
...全文
110 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Lionheartch 2013-04-07
  • 打赏
  • 举报
回复
引用 5 楼 starytx 的回复:
Cmessage & operator=(const Cmessage& amess) 返回值改成引用; 在析构里输出pmessage,看看就知道了,先析构的motto2,然后是motto1
多谢~
starytx 2013-04-07
  • 打赏
  • 举报
回复
Cmessage & operator=(const Cmessage& amess) 返回值改成引用; 在析构里输出pmessage,看看就知道了,先析构的motto2,然后是motto1
Lionheartch 2013-04-07
  • 打赏
  • 举报
回复
引用 3 楼 chuachua66 的回复:
moto2=moto1是调的赋值操作符, Cmessage motto2(moto1)才是调拷贝构造函数。 没有复制构造一说, 你跟下代码跟到重载的=里看看。
我写的比较乱。fuzhigouzao只是我随便输出的。motto2 = motto1确实是赋值操作符重载,重载没有问题, 但是motto2 = motto1结束后到cout<<"motto2 - " 中间motto2调用了析构函数。求解?
chuachua66 2013-04-07
  • 打赏
  • 举报
回复
moto2=moto1是调的赋值操作符, Cmessage motto2(moto1)才是调拷贝构造函数。 没有复制构造一说, 你跟下代码跟到重载的=里看看。
Lionheartch 2013-04-07
  • 打赏
  • 举报
回复
引用 1 楼 starytx 的回复:
何以见得motto2在那里调用析构了?
我用单步执行看的
starytx 2013-04-07
  • 打赏
  • 举报
回复
何以见得motto2在那里调用析构了?

64,639

社区成员

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

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