关于析构函数被调用后,构建的对象还存在吗?
#include <iostream>
using namespace std;
class Ex{
public:
Ex(int n)
{
i=n;
cout<<"Constructing \n";
}
~Ex()
{
cout<<"Destructing \n";
}
int get_i()
{
return i;
}
private:
int i;
};
int sqr(Ex ex)
{
return ex.get_i() * ex.get_i();
}
int main()
{
Ex x(2);
cout<<x.get_i()<<endl;
cout<<sqr(x)<<endl;
return 0;
}
运行结果:
Constructing
2
Destructing
4
Destructing
请高手们介绍一下程序流程调用析构函数的过程,及对象在内存的状态。为什么调用析构函数后,对象仍存在,而且两次调用析构函数(可能我的理解有误,请高手赐教)
[解决办法]
再运行下面的代码试试(注意代码中的注释)
#include <iostream>using namespace std;class Ex{public: Ex(int n) { i = n; cout << "Constructor" << endl; } Ex(const Ex& x) { i = x.i; cout << "Copy Constructor" << endl; } ~Ex() { cout << "Destructor" << endl; } int get_i() { return i; }private: int i;};int sqr(Ex& ex) // 如果将原来的int sqr(Ex ex)改成int sqr(Ex& ex)就不会调用拷贝构造函数了{ return ex.get_i() * ex.get_i();}int main(){ Ex x(2); cout << x.get_i() << endl; cout << "===" << endl; cout << sqr(x) << endl; cout << "===" << endl; return 0;}