我编写了这段代码来检查 c++ 中析构函数的行为
#include <vector>
#include <iostream>
using namespace std;
class WrongDestructor
{
private:
int number;
public:
WrongDestructor(int number_) :
number(number_)
{}
~WrongDestructor() {
cout<<"Destructor of " <<number<<endl;
// throw int();
}
};
int main(int argc, char *argv[])
{
std::vector<WrongDestructor> wrongs;
for(int i = 0; i < 10; ++i) {
wrongs.push_back(WrongDestructor(i));
}
return 0;
}
我发现有趣的是我的程序的输出:
Destructor of 0
Destructor of 0
Destructor of 1
Destructor of 0
Destructor of 1
Destructor of 2
Destructor of 3
Destructor of 0
Destructor of 1
Destructor of 2
Destructor of 3
Destructor of 4
Destructor of 5
Destructor of 6
Destructor of 7
Destructor of 0
Destructor of 1
Destructor of 2
Destructor of 3
Destructor of 4
Destructor of 5
Destructor of 6
Destructor of 7
Destructor of 8
Destructor of 9
Destructor of 0
Destructor of 1
Destructor of 2
Destructor of 3
Destructor of 4
Destructor of 5
Destructor of 6
Destructor of 7
Destructor of 8
Destructor of 9
这意味着创建的对象比我想象的要多得多。当我在 for 循环中填充集合时,我希望集合中显然有 10 个,并且可能会创建下 10 个作为临时对象。但是它们的数量更多,其中一些甚至比其他更频繁地创建。