dimanche 4 juin 2017

Why emplace_back does matter?

#include <iostream>
#include <vector>

struct T{
    T(){
        std::cout << "Constructor\n";
    }
    ~T(){
        std::cout << "Destructor\n";
    }   
};

int main() {
    std::vector<T> vec;
    vec.push_back(T());
    vec.push_back(T());

    return 0;
}

The output is:

(1)Constructor
(2)Destructor
(3)Constructor
(4)Destructor
(5)Destructor
(6)Destructor
(7)Destructor

Why there is so much desructors calls? I see that:

(1) consruct temporary object temp1

(2) destruct temp1

(3) consruct temporary object temp2

(4) destruct temp2

Then it was called copy constructor or move constructor for temp1 and temp 2. So, (5) and (6) are clear. But what about (7)?

Aucun commentaire:

Enregistrer un commentaire