I have a struct, say
struct A {
A(int n) : n(n) {}
int n;
};
and I want to initialize a std::vector
with some elements. I can do this by using an initialization list, or by emplacing the new elements:
// 3 ctors, 3 copy ctors, 3 dtors
std::vector<A> v1{1, 2, 3};
// 3 ctors
std::vector<A> v2;
v2.reserve(3);
v2.emplace_back(4);
v2.emplace_back(5);
v2.emplace_back(6);
As the comments show, the first version calls 3 constructors, 3 copy constructors, and 3 destructors. The version with emplace only uses 3 constructors.
Question: Can I do a direct initialization without the extra cost?
(Here's a longer version of the A
struct that shows what's happening.)
Aucun commentaire:
Enregistrer un commentaire