11

I was viewing the MSDN doc about multimap and find that it has a member function multimap::emplace(). Below is the example of that member function.

int main( ) {
   using namespace std;
   multimap<int, string> m1;
   pair<int, string> is1(1, "a");

   m1.emplace(move(is1));
}

It seems that emplace() and move() are C++0x. Can someone explain them for me? I read about move(), but I really don't understand what does it do (under the hood).

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
MorrisLiang
  • 702
  • 2
  • 7
  • 20
  • 2
    I recommend you to read : http://stackoverflow.com/questions/4303513/push-back-vs-emplace-back – Arzar Mar 29 '11 at 17:36

1 Answers1

16

Emplacing is easier to understand with vectors. my_vector.emplace_back(1, 2, 3) is basically an efficient shortcut for my_vector.push_back(some_type(1, 2, 3)). Instead of copy-constructing the object in-place, any constructor can now be used for in-place-construction, thus saving the creation, copy (or move) and destruction of a temporary object. Emplacing is powered by perfect forwarding.

std::move(expression) is basically a cast to an xvalue, which effectively allows the entire expression to be bound to an rvalue reference. You typically do this to enable resource pilfering from named objects that you are no longer interested in because they are going to be destroyed soon, anyway.

Community
  • 1
  • 1
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • I belive, that instead `my_vector.emplace(1, 2, 3)` should be `my_vector.emplace_back(1, 2, 3)` – UmmaGumma Mar 29 '11 at 12:30
  • 4
    This is a better answer than the accepted answer, which at the very least is inaccurate and arguably wrong. – Howard Hinnant Mar 29 '11 at 13:49
  • So isn't there a typo in msdn doc? I would think that a more explicit example to explain emplace would be `m1.emplace(1, "a")`, i.e. `emplace` forwards the arguments. It seems to me that their example would compile as well with `insert` instead of `emplace`. – rafak Apr 01 '11 at 14:58