jeudi 15 août 2019

Difference between stack initialization and emplace_back

What is the difference between the following 2 snippets of code?

Client w1(IPFamily::IPv4, apn0);
Client w2(IPFamily::IPv4, apn1);
w1.setEventReport(true);
w2.setEventReport(true);

and

vector<Client> clients;
clients.emplace_back(IPFamily::IPv4, apn0);
clients.emplace_back(IPFamily::IPv4, apn1);
clients[0].setEventReport(true); // This line throws exception
clients[1].setEventReport(true);

I thought they should behave identically, but in fact the second one throws an exception in practice while the first one works. I am at a loss as to what I'm missing here.

Note that this works:

vector<Client> clients;
clients.emplace_back(IPFamily::IPv4, apn0);
clients[0].setEventReport(true);
clients.emplace_back(IPFamily::IPv4, apn1);
clients[1].setEventReport(true);

Is emplace_back doing some extra magic I need to know about vs. stack based initialization?

Aucun commentaire:

Enregistrer un commentaire