move assignment

closed account (jGAShbRD)
template <typename Type>
my_unique_ptr<Type>& my_unique_ptr<Type>::operator=(my_unique_ptr &&target){
if (raw_pointer == nullptr)
delete raw_pointer;
raw_pointer = target.raw_pointer;
target.raw_pointer = nullptr;
return *this;
}

would this be the correct way to implement a move assignment?
1
2
if (raw_pointer == nullptr)
delete raw_pointer;

Nope.

-Albatross
It's almost ok. You forgot the check for self assignment.
closed account (jGAShbRD)
@albatross do i delete that? and @kbw what do u mean self assigment do u mean like
if(raw_pointer = raw_pointer)
delete raw_pointer;
1. If raw_pointer is already nullptr, there is nothing to delete. And there is no problem deleting a nullptr, so go ahead and just delete raw_pointer.

2. Self assignment. If in your code you do my_unique_ptr a(somePtrValue); a = std::move(a);, you will end up deleting your data but maintaining a pointer to this memory after the function is complete. This is a dangling pointer and leads to memory corruption.

Instead, at the very beginning of the function, check to see if both raw_pointer and target.raw_pointer are the same. If they are, you are self-assigning, and you can just return.
closed account (jGAShbRD)
template <typename Type>
my_unique_ptr<Type>& my_unique_ptr<Type>::operator=(my_unique_ptr &&target){
if (raw_pointer == nullptr || raw_pointer == raw_pointer)
delete raw_pointer;
raw_pointer = target.raw_pointer;
target.raw_pointer = nullptr;
return *this;
}
PLEASE use code tags when posting code, to make it readable.

You've already been asked this at least once. Why are you refusing to do so?
closed account (jGAShbRD)
by code tags do u mean what the function is doing?
No. I mean the thing for which I took the time and effort to provide you with a link, in your last thread.
How to use code tags:

http://www.cplusplus.com/articles/jEywvCM9/

Now read this and follow the instructions.
Topic archived. No new replies allowed.