析构函数调用问题

[复制链接]
1245|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

粉丝
快速回复 在线客服 返回列表 返回顶部