推入C++向量时的构造函数和析构函数调用
Constructor and destructor calls when pushing on to a C++ vector
对于以下代码
struct MyInt {
MyInt() {
std::cout << "I am the constructor for " << val << "n";
}
~MyInt() {
std::cout << "I am the destructor for " << val << "n";
}
int val;
};
int main() {
using namespace std;
cout << "Constructing l:" << endl;
vector<MyInt /*, Mallocator<MyInt>*/ > l;
MyInt int1;
MyInt int2;
int1.val = 1729;
int2.val = 2161;
cout << "Push back the itemn";
l.push_back(int1);
l.push_back(int2);
return 0;
}
为什么我得到以下输出?
Constructing l:
I am the constructor for 1558899544 (garbage)
I am the constructor for 47517696 (garbage)
Push back the item
I am the destructor for 1729
I am the destructor for 2161
I am the destructor for 1729
I am the destructor for 1729
I am the destructor for 2161
我假设有四个构造函数(两个用于 int1 和 int2,两个用于 push_back)和四个析构函数。有五个析构函数让我感到惊讶。
您只看到两个" I am the constructor for...
",因为您忘记添加复制构造函数:
MyInt(const MyInt& rhs)
{
std::cout << "I am the constructor copyn";
val = rhs.val;
}
你会看到 5 个析构函数,因为重新分配,正如 Barry 在他的回答中提到的。您可以reserve
向量的大小,您将只看到预期的 4 个析构函数:
l.reserve(2); // 2 will suffice for the example at hand
将其添加到代码中可能会输出(正如PaulMcKenzie指出的那样,编译器可以自由删除复制结构,因此最终输出可能取决于编译器,编译器设置,优化):
Constructing l:
I am the constructor default
I am the constructor default
Push back the item
I am the constructor copy
I am the constructor copy
I am the destructor
I am the destructor
I am the destructor
I am the destructor
五个析构函数:
int1
和int2
各两个main()
- 一个用于
l
内部的对象,当它必须被重新分配以容纳更多的成员时。 - 两个为
l
持有的MyInt
。
相关文章:
- 析构函数调用
- 在具有向量的类构造函数中进行析构函数调用
- 从 c++ 中派生类的析构函数调用虚函数
- C++析构函数调用两次,堆栈分配的复合对象
- C++ 在析构函数调用之前删除的动态成员数组
- 析构函数调用c++中的一个向量
- Singleton模式中的手动析构函数调用:调用多次
- 从内部类的析构函数调用虚拟函数
- 与 boost odeint 集成期间的析构函数调用
- 堆栈展开如何与析构函数调用有关?
- C++:优化析构函数调用
- 以逗号分隔的表达式中的析构函数调用
- GCC 9.1 返回 void& 作为显式析构函数调用的结果类型。这是一个错误吗?
- 从C++中的虚拟析构函数调用虚拟方法
- 从指针返回对象时出现意外的析构函数调用
- 使用 decltype 显式析构函数调用
- C++析构函数调用了错误的对象
- 了解虚拟函数和析构函数调用
- 多重继承析构函数调用他自己和父析构函数?c++
- 析构函数调用表单不适当的库