Move assignment operator: Difference between revisions

Content deleted Content added
C++Bro123 (talk | contribs)
Monospace
 
(8 intermediate revisions by 7 users not shown)
Line 1:
{{Short description|Operator used in C++}}
In the [[C++|C++ programming language]], the '''move assignment operator''' <code>=</code> is used for transferring a temporary object to an existing object. The move assignment operator, like most C++ operators, can be [[Operator overloading|overloaded]]. Like the [[copy assignment operator]] it is a [[special member functions|special member function]].
 
If the move assignment operator is not explicitly defined, the [[compiler]] generates an implicit move assignment operator ([[C++11]] and newer) provided that [[Copy constructor (C++)|copy]]/[[move constructor]]s, [[Assignment operator (C++)|copy assignment operator]] or [[Destructor (computer programming)|destructors]] have not been declared.<ref name=":0" /> The parameter of a move assignment operator is an [[rvalue reference]] ({{Mono|T&&}}) to type ''T'', where ''T'' is the object that defines the move assignment operator. The move assignment operator is different than a [[move constructor]] because a move assignment operator is called on an existing object, while a move constructor is called on an object created by the operation. Thereafter, the other object's data is no longer valid.
 
== Overloading move assignment operator ==
To overload the move assignment operator, the signature of the function must be:<ref name=":0">{{Cite web|title = Move assignment operator - cppreference.com|url = http://en.cppreference.com/w/cpp/language/move_assignment|website = en.cppreference.com|access-date = 2016-02-23}}</ref><syntaxhighlight lang="c++">
T& operator=(T&& data)
</syntaxhighlight>To successfully overload the move assignment operator, the following conditions must be met:
Line 10 ⟶ 11:
* The current object's data is de-allocated.
* The object that is being moved from must have its data marked as [[nullptr]] (or something to signify the move)
* The operator must return a reference to "{{Mono|*this}}".
 
Consider 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 String {
public:
String& operator=(String&& other) noexcept {
// If we're not trying to move the object into itself...
if (this != &other) {
delete[] this->data_; // DeleteFree thethis string's original data.
this->data_ = other.data_; // Copy the other string's data pointer into this string.
other.data_ = nullptr; // Finally, reset the other string's data pointer.
}
Line 32 ⟶ 33:
==References==
<references />
 
{{C++ programming language}}
 
[[Category:C++]]