为什么c++类的析构函数在构造时调用
Why is the destructor of a C++ class called upon construction?
我遇到的问题是,我的类析构函数在类构造时被调用。考虑以下测试程序:
#include <iostream>
#include <vector>
using namespace std;
class X
{
public:
X() { cout << "X::X()" << endl; };
~X() { cout << "X::~X()" << endl; };
};
class Y : public X
{
public:
Y() : X() { cout << "Y::Y()" << endl; };
~Y() { cout << "Y::~Y()" << endl; };
};
int main() {
vector<Y> a;
a.resize(10);
while(true) ;
return 0;
}
循环前的输出是
X::X()
Y::Y()
Y::~Y()
X::~X()
我不明白上面代码片段的行为:
- 为什么只构造一个元素? 为什么要调用析构函数?
std::vector::resize()
的原型为:
void resize( size_type count, T value = T() );
因此它创建了一个临时的默认值插入到vector中(你的构造函数调用),然后在vector中复制构造10次(你不记录这些),然后销毁这个临时值(你的析构函数调用)。
请注意,c++ 11中发生了变化。现在有两个重载:
void resize( size_type count );
void resize( size_type count, const value_type& value);
所以,如果你使用一个合适的c++ 11编译器,你将调用第一个重载,你的值将被值初始化,也就是说,它将使用默认构造函数
相关文章:
- 什么时候调用析构函数
- C++-明确何时以及如何调用析构函数
- C++ 防止在映射中放置()时调用析构函数
- 调用析构函数以释放动态分配的内存
- C++:使用方法调用析构函数的顺序是什么?
- 向量推回调用析构函数时调用析构函数
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- C++,我应该调用析构函数吗?
- 如何获取有关在 Clang LibTooling 中调用析构函数的信息?
- 当我从 std::vector 中的新放置调用析构函数时会发生什么?
- 为什么这里不调用析构函数
- 在调用 std::bind 的产品后意外调用析构函数
- 为什么在传递给函数而不是构造函数时调用析构函数?
- 如何在C++中调用析构函数
- 为什么为未删除的对象调用析构函数?
- 调用析构函数时出错
- C++ 在不释放内存的情况下调用析构函数
- 为什么在运算符删除中不调用析构函数?
- C++ 调用析构函数后动态模板队列"double free or corruption (out)"
- 在 postOrderDelete 上调用析构函数时引发的异常