Move value from local stack to heap? (C++)
An object is identified by its address. If you want it at another address, you have to construct a new one; you can't move objects. (Even with C++11, the new “move” semantics don't actually move an object; they provide an optimized way of moving its value, if you know that you won't need the value from where you're moving it.)
Firstly, you should prefer the stack to the heap in most cases.
Secondly, when you allocate objects on the heap you should wrap the raw pointer in some managed object which is on the stack. If for nothing else, do it for exception safety.
Thirdly, Qt objects usually do exactly that i.e. there's no advantage in writing new QImage
or new QMap<int>
etc.
Nevertheless the right way to move a non-heap object onto the heap is to say
new ObjectType (old_instance)
If you do this with a temporary object, such as
new ObjectType (create_object ())
then it will probably elide the extra copy (link broken for me -- cached)