【发布时间】:2015-06-28 18:00:47
【问题描述】:
我尝试运行下面的代码,但我不明白析构函数何时以及为何在myA=foo(myOtherB) 行被调用。
我的问题是,在 foo 函数返回 A 对象之后,从“输入”复制构造它并打印 A 复制器,operator= 被称为打印“Aop”,然后析构函数被称为打印 A dtor。
为什么此时调用析构函数而不是在operator=调用之前的返回之后?
我遇到的另一个问题是,如果我使用 return A(2) 而不是 return input
构造函数 A 不会被调用打印 A ctor...
谁能解释一下?抱歉代码有点复杂。
#include <iostream>
using namespace std;
class A
{
public:
int x;
A(){ cout<<"A ctor"<<endl; }
A(const A& a){cout<<"A copyctor"<<endl; }
virtual~A(){ cout<<"A dtor"<<endl;}
virtual void foo(){ cout<<"Afoo()"<<endl;}
virtual A& operator=(const A&rhs){cout<<"Aop="<<endl; }
A(int _x)
{
x=_x;
}
};
class B:public A
{
public:
B(){ cout<<"B ctor"<<endl; }
virtual~B(){ cout<<"B dtor"<<endl; }
virtual void foo(){ cout<<"B foo()"<<endl; }
protected:
A mInstanceOfA;
};
A foo(A& input)
{ input.foo(); return input; //return A(2); does not call the A constructor }
int main()
{
B myOtherB;
A myA;
myA=foo(myOtherB);
}
【问题讨论】:
标签: c++ constructor destructor