Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move an object into uninitialized memory?

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?

like image 819
user541686 Avatar asked Jul 24 '12 13:07

user541686


1 Answers

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();
like image 165
Mike Seymour Avatar answered Nov 15 '22 06:11

Mike Seymour