Search code examples
c++stlcontainersemplace

How to emplace object without constructor arguments to STL constainer?


Suppose I have an class that has constructor taking no arguments, and an STL container of its objects: list<Object> lst; Is there a way to insert a new object in-place?

I know something like lst.push_back(Object()); is going to work, equally fast as it would use move constructor, however it seems a little bit odd that there is no function to simply create new object at the end of the list without any arguments, while there already is emplace that could fit that place.

Could you please, provide some explanation if it isn't actually possible?


Solution

  • Well, emplace_back() does exactly that.

    Just use lst.emplace_back(); and that function will create an object in place at the end of the list.