析构函数的调用时间

Lionheartch Lionheartch 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
对象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.
...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
Lionheartch
C++ 语言 65,212 成员 250,513 内容