Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I perfectly forward arguments to a STL collection?

How can I perfectly forward arguments for the creation of objects to a STL collection?

I would like to avoid unnecessary copies. While I can avoid this by storing pointers, I do not want to use dynamic memory.

struct MyFatClass
{
    explicit MyFatClass(int a) {...}
    ...
}; 

std::vector<MyFatClass> records;
records.emplace_back(MyFatClass(1000)); // How can I avoid this temporary object? 
like image 549
Nathan Doromal Avatar asked Feb 14 '23 21:02

Nathan Doromal


1 Answers

You don't actually need to create a temporary when using std::vector::emplace_back, that's exactly what emplace_back is used for:

records.emplace_back(1000);

This will construct a MyFatClass object in-place, avoiding temporaries and extra copies.

like image 93
mfontanini Avatar answered Feb 17 '23 10:02

mfontanini