Search code examples
c++performancevectorconstructorplacement-new

Can I add to a vector using placement new


I have a vector of MyClass, where MyClass is a large class. When I do:

vector<MyClass> vec;
vec.push_back(MyClass(a,b,c));

this seems quite inefficient, as a temporary MyClass is created, copied into the vector, then destructed.

Is there some way to use placement new to create the class directly inside the vector in the first place? I can't do it like this:

vector<MyClass> vec;
vec.resize(1);
new(&vec.data[0]) MyClass(a,b,c);

because vec.resize(1) calls the MyClass constructor. Is there some way to resize a vector without it calling constructors for all the new items, or is it possible to construct MyClass directly into the vector in the next available place?


Solution

  • No, but you can use emplace_back to build the object in place:

    vec.emplace_back(a,b,c);