【发布时间】:2021-06-21 23:28:27
【问题描述】:
我写了两个程序来理解复制对象的概念。 第一个:
#include<bits/stdc++.h>
using namespace std;
class myInt
{
int x;
public:
myInt()
{
cout<< "default constructor is called" << endl;
}
myInt(int x)
{
cout<< "constructor is called with initializer" << endl;
this->x = x;
}
~myInt()
{
cout<< "destructor is called" << endl;
}
};
myInt func(myInt ob)
{
return ob;
}
int main()
{
myInt ob1(2);
func(ob1);
}
输出:
constructor is called with initializer
destructor is called
destructor is called
destructor is called
这里析构函数被调用了 3 次,这意味着创建了 3 个对象。一个用于对象“ob1”,一个用于 func() 内部的“ob”,另一个用于从 func() 返回“ob”。 我的第二个代码:
#include<bits/stdc++.h>
using namespace std;
class myInt
{
int x;
public:
myInt()
{
cout<< "default constructor is called" << endl;
}
myInt(int x)
{
cout<< "constructor is called with initializer" << endl;
this->x = x;
}
~myInt()
{
cout<< "destructor is called" << endl;
}
};
myInt func(myInt ob)
{
return ob;
}
int main()
{
myInt ob1(2);
myInt ob2 = func(ob1);
}
输出:
constructor is called with initializer
destructor is called
destructor is called
destructor is called
这里还创建了 3 个对象作为第一个对象。但是,当我将来自 func() 的返回对象存储在其中时,不应该再调用一个 'ob2' 的析构函数吗?为什么两种情况下析构函数调用的次数相同?
【问题讨论】:
-
返回值优化:
ob2并没有真正创建。另请参阅:copy elision. -
看看这个question。
标签: c++ class object destructor