samedi 26 août 2017

How to explain that there are 9 times of destruction?

I want to learn what differences are between push_back() and emplace_back(), especially when the elements are class type.So I write code like following:

int cnt = 0;
class foo{
public:
    //constructor
    foo() : ucnt(++cnt) { cout << ucnt << "\tdefault" << endl; }
    foo(const foo&) : ucnt(++cnt) { cout << ucnt << "\tcopy" << endl; }
    ~foo() { cout << ucnt << "\tdestroyed" << endl; }
    int ucnt;
};

int main()
{
    vector<foo> vf = {foo()};
    cout << vf.size() << " : " << vf[0].ucnt << endl;
    vf.push_back(foo());
    cout << vf.size() << " : " << vf[0].ucnt << " " << vf[1].ucnt << endl;
    vf.emplace_back(foo());
    cout << vf.size() << " : " << vf[0].ucnt << " " << vf[1].ucnt << " " << vf[2].ucnt << endl;
    return 0;
}

whose result is:

1       default
2       copy
1       destroyed
1 : 2
3       default
4       copy
5       copy
2       destroyed
3       destroyed
2 : 5 4
6       default
7       copy
8       copy
9       copy
5       destroyed
4       destroyed
6       destroyed
3 : 8 9 7
8       destroyed
9       destroyed
7       destroyed

It seems like all the elements in vf are copyed and then destroyed while executing push_back() and emplace_back().Why?

Aucun commentaire:

Enregistrer un commentaire