Move assignment operator: Difference between revisions

Content deleted Content added
Overloading move assignment operator: Based on the MS link. Assuming text is more than one char.
Clean up examples
Line 14:
An implementation of the move assignment operator:<ref>{{Cite web|title = Move Constructors and Move Assignment Operators (C++)|url = https://msdn.microsoft.com/en-us/library/dd293665.aspx|website = msdn.microsoft.com|access-date = 2016-02-23}}</ref><syntaxhighlight lang="c++">
class Resource {
void* data;
 
public:
 
Resource& operator=(Resource&& other) {
if (this != &other) { // If the object isn't being called on itself...
if (this != &other) {delete this->data; // IfDelete the object isn't being calleds onoriginal itselfdata.
delete this->data; = other.data; // DeleteCopy the other object's data into this object.
this->other.data = other.datanullptr; // "Move"Finally, reset the other object's data into the current objectpointer.
other.data = nullptr; // Mark the other object as "empty"
}
return *this; // return *this
}
 
void* data;
 
};
</syntaxhighlight>A more practical example:<syntaxhighlight lang="c++">
class String {
char* text;
 
public:
 
String& operator=(String&& otherString) {
if (this != &otherString) {
delete[] text;
Line 44 ⟶ 39:
return *this;
}
 
char* text;
 
};
</syntaxhighlight>