Move assignment operator: Difference between revisions

Content deleted Content added
No edit summary
Remove a redundant example
Line 12:
* The operator must return a reference to "*this".
 
An implementation ofConsider the following move assignment operator for a simple string class:<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 ResourceString {
voidchar* data;
 
public:
ResourceString& operator=(ResourceString&& other) {
if (this != &other) { // If we're not trying to move the object into itself...
delete this->data; // Delete the objectstring's original data.
this->data = other.data; // Copy the other objectstring's data into this objectstring.
other.data = nullptr; // Finally, reset the other objectstring's data pointer.
}
return *this;
}
};
</syntaxhighlight>A more practical example:<syntaxhighlight lang="c++">
class String {
char* text;
public:
String& operator=(String&& otherString) {
if (this != &otherString) {
delete[] text;
this->text = otherString.text;
otherString.text = nullptr;
}
return *this;
}
};
</syntaxhighlight>
 
==References==
<references />