我正在试图弄清楚构造函数和析构函数何时被调用。示例代码:
#include <iostream>
using namespace std;
class A{
public:
A();
A(int);
A operator+(const A& rhs) const;
~A();
public:
int x;
};
A A::operator+(const A& rhs) const
{
A r(x + rhs.x);
cout<<"end A operator"<<endl;
return r;
}
A::A(int y): x(y)
{
cout<<"Constructor A called"<<endl;
}
A::~A()
{
cout<<"Destructor A called"<<endl;
}
//////////
class B{
public:
B();
B(int);
B operator+(B rhs) const;
~B();
public:
int x;
};
B B::operator+(B rhs) const
{
cout<<"beginning B operator"<<endl;
return B(x + rhs.x);
}
B::B(int y): x(y)
{
cout<<"Constructor B called"<<endl;
}
B::~B()
{
cout<<"Destructor B called"<<endl;
}
int main()
{
cout<<"line 1 main()"<<endl;
A a(1);
cout<<"line 2 main()"<<endl;
B b(2);
cout<<"\nline 3 main()"<<endl;
a = a + a;
cout<<"\nline 4 main()"<<endl;
b = b + b;
cout<<"\nend of main"<<endl;
}
所以当我打电话给我时,我得到了输出:
line 1 main()
Constructor A called
line 2 main()
Constructor B called
line 3 main()
Constructor A called
end A operator
Destructor A called
line 4 main()
beginning B operator
Constructor B called
Destructor B called
Destructor B called
end of main
Destructor B called
Destructor A called
所以我当然理解输出的第一个块。我明确地调用了两个构造函数。第二个代码块,有一个在你创建对象时被调用的A构造函数r
A r(x + rhs.x);
然后是第3块输出代码。在这行代码中调用构造函数B.
return B(x + rhs.x);
答案 0 :(得分:0)
在第二个代码块中,当变量r超出范围时,将调用A的析构函数。
在第三个代码块中,您实际上构建了两个B对象。第一个是构造的,因为你通过值传递B in,它调用复制构造函数。编译器创建的默认复制构造函数不包含打印出“构造函数B调用”的代码,因此您没有看到在输出中调用构造函数。正如你所说,在返回行上调用第二个构造函数,之后返回值和rhs变量都超出范围,并且为两个对象调用析构函数。