Re:Move, simply
by gpu_explorer on Monday February 17, 2020 @03:09PM
(#22350288)
I found it's much easier to understand the concepts behind move operations if you write an object that implemented move semantics by itself.
I think much of the confusion arises from wondering where is the allocation for int* data located? It's somewhere on the heap. What if the data member were int data[32] instead? What would the class look like? What would 'a' look like afterwards?
[ Parent
| on HN ]
I appreciate it's just an example, but it should be mentioned that this is a really bad class. If you write a custom destructor, you must also specify the move/copy constructors and move/assignment operators. Otherwise, the same data pointer will be deleted twice if the object is ever copied.
Re:Move, simply
by gpu_explorer on Monday February 17, 2020 @06:45PM
(#22352071)
Yes I know this of course but it seemed that leaving things out is faster and people can know it's just a toy.
Don't you have to destroy the target object, before you move into it?
Re:Move, simply
by gpu_explorer on Monday February 17, 2020 @03:20PM
(#22350377)
In this example no because of pointer. Where is the allocation for int* data located? It's not inside the object. You can think easily of the state of 'a' after calling move_into.
But maybe with int data[32] as a data member this is harder to reason about.
This is a way to illustrate move semantics and confusion behind what happens to the 'moved from' object.
Re:Move, simply
by AnimalMuppet on Monday February 17, 2020 @03:53PM
(#22350640)
You made the moved-to pointer point to the moved-from allocated heap data. Now nothing points to the heap data that was initially allocated by the moved-to object. So if you don't delete[] the moved-to data pointer, then you leaked 32 bytes of heap.
Re:Move, simply
by gpu_explorer on Monday February 17, 2020 @04:00PM
(#22350709)
What happens when the program exits?
Re:Move, simply
by AnimalMuppet on Monday February 17, 2020 @04:03PM
(#22350727)
Then it doesn't matter. It matters if you run out of heap before the program exits, though.
No, you don't have to destroy the target object. You may need to destroy some of its members depending on the object implementation.
Re:Move, simply
by marksmith2996 on Monday February 17, 2020 @11:19PM
(#22353420)
Yes, this is a memory leak.
Why would you alter data (set it to nullptr) in a destructor?
Re:Move, simply
by gpu_explorer on Monday February 17, 2020 @04:07PM
(#22350772)
From my copy paste example. I fixed thank you.