打印

析构函数调用问题

[复制链接]
753|3
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
gxgclg|  楼主 | 2013-10-29 20:11 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
写了一个类,简化是如下
class A{
int data;
public:
A(int data){
cout<<"无参数构造函数,data="<<data<<"\n";
this->data=data;
}
A(const A &other){
cout<<"复制构造函数,data="<<data<<"\n";
data=other.data;
}
~A(){
cout<<"data="<<data<<"的对象死了!\n";
}
A&operator=(const A&other){
if(this==&other)
   return;
data=other.data;
cout<<"赋值\n";
}
}
int main(){
A a1(1);
A a2=a1;
A a3(3);
a3=a2;
return 0;
}
运行一下,会很神奇的发现,a3,a2都可以正常被弄死,可是a1很神奇的消失了。这个对象的析构函数没有被调用?!这是什么原因??

相关帖子

沙发
xsgy123| | 2013-10-29 22:36 | 只看该作者
A&operator=(const A&other)
{
    if(this==&other)
        return *this;
        data=other.data;
    cout<<"赋值\n";
    return *this;
}
=赋值函数应该像上面这样
你确定你的代码可以编译通过?

使用特权

评论回复
板凳
dfsa| | 2013-10-30 16:37 | 只看该作者
没看太明白

使用特权

评论回复
地板
sinadz| | 2013-10-30 16:48 | 只看该作者
很容易出错的问题

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

177

主题

1653

帖子

1

粉丝