我运行了下面的代码
#include <iostream>
using namespace std;
class Count
{
private:
int count;
public:
//Constructor
Count():count(0) { cout << "Constructor called" << endl; }
//Destructor
~Count() { cout << "Destructor called" << endl; }
//Display the value.
Count display()
{
cout << "The value of count is " << count << endl;
return *this;
}
};
int main()
{
Count C;
C.display();
}
结果:-
Constructor called
The value of count is 0
Destructor called
Destructor called
在上面的例子中,析构函数被调用了两次,一次用于销毁“this”对象,一次用于从 main 返回。
我的观察是否正确??
任何人都可以向我解释在此过程中创建的临时对象,例如创建它的原因(如果创建的话)?
最佳答案
您正在从 display()
方法返回一个拷贝,因此它也需要被销毁。因此,在您的主体中,您实际上有 2 个对象,一个是隐含的。
关于c++ - 这些析构函数调用背后的逻辑是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30544694/