简体   繁体   中英

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

I am having the problem that my class destructor is called when the class is constructed. Consider the following test program:

#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;
}

The output (from before the loop) is

X::X()
Y::Y()
Y::~Y()
X::~X()

I don't understand the behaviour of the above snippet:

  1. Why is only a single element constructed?
  2. Why are the destructors called?

The prototype of std::vector::resize() is:

void resize( size_type count, T value = T() );

So it creates a temporary default value to be inserted into the vector (your constructor call), then it is copy-constructed 10 times into the vector (you do not log those), and then the temporary is destroyed (your destructor call).

Note that things have changed for C++11. Now there are two overloads:

void resize( size_type count );
void resize( size_type count, const value_type& value);

So, if you use a proper C++11 compiler you will call the first overload and your values will be value-initialized, that is it will use the default constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM