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?
            Asked
            
        
        
            Active
            
        
            Viewed 578 times
        
    5
            
            
        - 
                    by "move" do you mean copy object? – Moataz Elmasry Jul 24 '12 at 13:23
- 
                    4@MoatazElmasry No, he literally means [move](http://stackoverflow.com/questions/3106110/), not copy. – fredoverflow Jul 24 '12 at 13:31
1 Answers
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
- 
                    3Moving 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
- 
                    
- 
                    @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
