Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Move assignment operator

From Wikipedia, the free encyclopedia
Operator used in C++

In theC++ programming language, themove assignment operator= is used for transferring a temporary object to an existing object. The move assignment operator, like most C++ operators, can beoverloaded. Like thecopy assignment operator it is aspecial member function.

If the move assignment operator is not explicitly defined, thecompiler generates an implicit move assignment operator (C++11 and newer) provided thatcopy/move constructors,copy assignment operator ordestructors have not been declared.[1] The parameter of a move assignment operator is anrvalue reference (T&&) to typeT, whereT 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

[edit]

To overload the move assignment operator, the signature of the function must be:[1]

T&operator=(T&&data)

To successfully overload the move assignment operator, the following conditions must be met:

  • Check if the object calling the operator is not calling the operator on itself.
  • The current object's data is de-allocated.
  • The object that is being moved from must have its data marked asnullptr (or something to signify the move)
  • The operator must return a reference to "*this".

Consider the following move assignment operator for a simple string class:[2]

classString{public:String&operator=(String&&other)noexcept{// If we're not trying to move the object into itself...if(this!=&other){delete[]this->data_;// Free this 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.}return*this;}private:char*data_;};

References

[edit]
  1. ^ab"Move assignment operator - cppreference.com".en.cppreference.com. Retrieved2016-02-23.
  2. ^"Move Constructors and Move Assignment Operators (C++)".msdn.microsoft.com. Retrieved2016-02-23.
Features
Standard Library
Ideas
Compilers
IDEs
Superset languages
Dialects
Relative to
other languages
People
Stub icon

Thiscomputer-programming-related article is astub. You can help Wikipedia byadding missing information.

Retrieved from "https://en.wikipedia.org/w/index.php?title=Move_assignment_operator&oldid=1275001753"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp