1

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?

pkubik
  • 780
  • 6
  • 19

2 Answers2

7

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.

JBL
  • 12,588
  • 4
  • 53
  • 84
  • Thanks, it works. That was my first intuition however KDevelop suggested to make it `lst.emplace_back();` which for some reason didn't work. It's embarasing that among many versions I've tried wasn't this simpliest one. Btw. any idea why explicit type version didn't work? – pkubik Jul 17 '14 at 13:54
  • @pkubik That's a strange suggestion, because `emplace_back` is a variadic template only parameterized by the constructor arguments. So obviously this shouldn't work unless you have a constructor that takes an `Object` as its only argument. – JBL Jul 17 '14 at 13:59
  • That shouldn't make sense anyway to have to specify the type of the object to be constructed. This type is known as soon as you've declare the list. – JBL Jul 17 '14 at 13:59
2

You can use lst.emplace_back();

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91