0

I'm studying in what order constructors and destructors get called and I wrote that code:

#include <string>
#include <vector>
#include <iostream>

using namespace std;

class Corgi {

    private:
        string nickname;

    public:
        Corgi(): nickname("unknown") {
            cout << "Corgi object CREATED. Name: unknown" << endl;
        }
        Corgi(const string& _nickname): nickname(_nickname) {
            cout << "Corgi object CREATED.   \tName: " + nickname << endl;
        }
        string getName() { return nickname; }
        ~Corgi() { cout << "Corgi object DESTROYED. \tName: " << nickname << endl; }
};

int main() {
vector<Corgi> zoo;
    for (int i = 0; i < 5; i++)
        zoo.push_back(Corgi("Zoo Corgi_" + to_string(i)));

    return 0;
}

The output I get:

Corgi object CREATED.       Name: Zoo Corgi_0
Corgi object DESTROYED.     Name: Zoo Corgi_0
Corgi object CREATED.       Name: Zoo Corgi_1
Corgi object DESTROYED.     Name: Zoo Corgi_0
Corgi object DESTROYED.     Name: Zoo Corgi_1
Corgi object CREATED.       Name: Zoo Corgi_2
Corgi object DESTROYED.     Name: Zoo Corgi_0
Corgi object DESTROYED.     Name: Zoo Corgi_1
Corgi object DESTROYED.     Name: Zoo Corgi_2
Corgi object CREATED.       Name: Zoo Corgi_3
Corgi object DESTROYED.     Name: Zoo Corgi_3
Corgi object CREATED.       Name: Zoo Corgi_4
Corgi object DESTROYED.     Name: Zoo Corgi_0
Corgi object DESTROYED.     Name: Zoo Corgi_1
Corgi object DESTROYED.     Name: Zoo Corgi_2
Corgi object DESTROYED.     Name: Zoo Corgi_3
Corgi object DESTROYED.     Name: Zoo Corgi_4
Corgi object DESTROYED.     Name: Zoo Corgi_0
Corgi object DESTROYED.     Name: Zoo Corgi_1
Corgi object DESTROYED.     Name: Zoo Corgi_2
Corgi object DESTROYED.     Name: Zoo Corgi_3
Corgi object DESTROYED.     Name: Zoo Corgi_4

This output baffles me completely.

  • Why does Zoo Corgi_0 gets destroyed 5 times if it gets created only once?
  • Why does Zoo Corgi_0 gets created and immediately destroyed before even Zoo Corgi_1 is created?
  • What makes C++ destroy Zoo Corgi_0 again after creating Zoo Corgi_1?

In the output I expected 10 lines: 5 lines for creating Zoo Corgis from 0 to 4 and 5 lines for destructing these objects. But apparently the thing are much more complicated.

I appreciate any help.

alekscooper
  • 795
  • 1
  • 7
  • 19
  • 3
    TL:DR of the dupe: As the vector grows, it has to allocate new memory, move/copy, then add the new item. If you add a copy or move constructor and have it print, you'll see all the copies/moves being made. – NathanOliver Jan 02 '20 at 18:57
  • 1
    If using vectors, it's best to initialize it with a size if you know how big it'll be or a decent approximation. Additional recommended reading: [Initializing the size of a C++ vector](https://stackoverflow.com/questions/25108854/initializing-the-size-of-a-c-vector/25108894) – Enfyve Jan 02 '20 at 19:01

0 Answers0