为什么c++类的析构函数在构造时调用

Why is the destructor of a C++ class called upon construction?

本文关键字:调用 析构函数 c++ 为什么      更新时间:2023-10-16

我遇到的问题是,我的类析构函数在类构造时被调用。考虑以下测试程序:

#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()

我不明白上面代码片段的行为:

  1. 为什么只构造一个元素?
  2. 为什么要调用析构函数?

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编译器,你将调用第一个重载,你的值将被值初始化,也就是说,它将使用默认构造函数