samedi 1 mai 2021

Interesting extra destruction call during push_back in std::vector

I find the output of the following code very interesting.

class Name
{
  string _name;
public:
  Name(const string& name) : _name(name) { cout << "ctor of " << _name << endl; }
  ~Name(){ cout << "dtor of " << _name << endl; }
};
int main() {

  vector<Name> list;
  cout << "------------------START push_back" << endl;
  list.push_back(Name(string("A")));
  cout << "------------------push_back(A) performed..." << endl;
  list.push_back(Name(string("B")));
  cout << "------------------push_back(B) performed..." << endl;
  list.push_back(Name(string("C")));
  cout << "------------------push_back(C) performed..." << endl;
  cout << "------------------END push_back" << endl;

  return 0;
}

I can understand that push_back uses an extra temporary object which is why emplace_back is recommended for better performance. Can someone explain the extra destructor calls shown in the output below with (???) next to it.

------------------START push_back
ctor of A
dtor of A
------------------push_back(A) performed...
ctor of B
dtor of A(???)
dtor of B
------------------push_back(B) performed...
ctor of C
dtor of A(???)
dtor of B(???)
dtor of C
------------------push_back(C) performed...
------------------END push_back
dtor of A
dtor of B
dtor of C
------------------START emplace_back
ctor of A
------------------emplace_back(A) performed...
ctor of B
------------------emplace_back(B) performed...
ctor of C
------------------emplace_back(C) performed...
------------------END emplace_back()
dtor of A
dtor of B
dtor of C

Aucun commentaire:

Enregistrer un commentaire