5

Given an allocated but uninitialized memory location, how do I move some object into that location (destroying the original), without constructing potentially expensive intermediate objects?

user541686
  • 205,094
  • 128
  • 528
  • 886

1 Answers1

8

You could use placement new to move-construct it in the memory:

void * memory = get_some_memory();
Thing * new_thing = new (memory) Thing(std::move(old_thing));

If it has a non-trivial destructor, then you'll need to explicitly destroy it when you're done:

new_thing->~Thing();
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Whoa, I thought a move constructor needs the current object to be valid, so it can swap it with the temporary! Was I wrong? – user541686 Jul 24 '12 at 13:28
  • 3
    Moving and swapping are not the same thing at all. A move constructor *initializes* a new object from an already existing object, whereas swapping requires two existing objects. – fredoverflow Jul 24 '12 at 13:28
  • @FredOverflow: Ohhh... yeah.. it's my first time writing a move constructor so I thought I have to swap with the input (so that when it goes out of scope it takes everything with it) instead of just taking ownership.... that makes a lot of sense, thanks! – user541686 Jul 24 '12 at 13:30
  • Swapping makes perfect sense in the move assignment operator. – fredoverflow Jul 24 '12 at 13:30
  • @FredOverflow: Ahh... totally forgot about the move-assignment operator (never actually written one either)! Yeah now the distinction is clear... awesome, thanks! – user541686 Jul 24 '12 at 13:31