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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With