为什么在初始化和调整对象的向量时调用析构函数? [英] Why is the destructor called when initializing and resizing a vector of objects?
问题描述
在我的程序中发生了一些事,我找不到它是否应该发生。如果是,我不明白为什么..
Something occurred in my program, and I can't find if it's supposed to happen or not. And if it is, I don't see why..
以下是代码:
#include <iostream>
#include <vector>
using namespace std;
class A{
public:
A();
~A();
};
A::A(){
cout << "creating" << endl;
}
A::~A(){
cout << "deleting" << endl;
}
int main(void){
vector<vector<A > > vec;
vec.resize(5);
for(int i = 0; i < 5; ++i){
vec[i].resize(5);
}
cout << "END" << endl;
return 0;
}
这里是输出:
creating
deleting
creating
deleting
creating
deleting
creating
deleting
creating
deleting
END
deleting
deleting
[..more deleting here]
我理解为什么在END消息之后调用析构函数,但之前,我不知道。我想,当向量调整大小时,类的构造函数被调用,但为什么是析构函数?
I understand why the destructor is called after the "END" message, but before, I don't. I thought that when the vector resize, the constructor of the class is called, but why the destructor?
推荐答案
03 向量< A> :: resize()
有一个默认值,默认值为 A()
。这是暂时的,被毁了。
In C++03 vector<A>::resize()
has a default parameter, with default value A()
. It's this temporary that's destroyed. The elements of the vectors are copy constructed from it.
在C ++ 11中这是fixed,其中有两个重载 resize
。一个具有单个参数,并且值初始化任何附加元素。另一个有两个参数,并从提供的值复制初始化每个附加元素。在C ++ 11中,此程序具有以下行为:
This is "fixed" in C++11, where there are two overloads of resize
. One has a single parameter, and value-initializes any additional elements. The other has two parameters, and copy-initializes each additional element from the value supplied. In C++11 this program has this behavior:
creating
creating
creating
<repeated for a total of 25 "creating"s>
creating
creating
creating
END
deleting
deleting
deleting
<repeated for a total of 25 "deleting"s>
deleting
deleting
deleting
如果一个 A
的实例是非常昂贵的构造,它是值得最小化的数字,那么你可以从5 no-args- + 25复制结构到1没有arg和25个具有这样的东西的拷贝结构:
In C++03, if an instance of A
is so shockingly expensive to construct that it's worth minimizing the number, then you could shave it from 5 no-args- + 25 copy-constructions down to 1 no-arg- and 25 copy-constructions with something like this:
A default_value;
for (int i = 0; i < 5; ++i) {
// same end result as vec[i].resize(5)
if (vec[i].size() >= 5) {
vec[i].erase(vec.begin() + 5, vec.end());
} else while(vec[i].size() < 5) {
vec[i].push_back(default_value);
}
}
您可以写得稍有不同,你的示例代码你不需要ifcase。但我没有很多机会说别的时候,所以我承担。
You can probably write it slightly differently, and obviously for your example code you don't need the "if" case. But I don't get many opportunities to say "else while", so I'm taking it.
这篇关于为什么在初始化和调整对象的向量时调用析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!