Move assignment operator
Материал из cppreference.com
|
|
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
Оператор ход присвоения класса
T не является шаблоном не статические функции-члены с именем operator=, которая принимает один параметр типа T&&, const T&&, volatile T&&, или const volatile T&&. Типа с общественностью оператора присваивания шаг MoveAssignable.Original:
A move assignment operator of class
T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T&&, const T&&, volatile T&&, or const volatile T&&. A type with a public move assignment operator is MoveAssignable.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Содержание |
[править] Синтаксис
class_name & class_name :: operator= ( class_name && )
|
(1) | (начиная с C++11) | |||||||
class_name & class_name :: operator= ( class_name && ) = default;
|
(2) | (начиная с C++11) | |||||||
class_name & class_name :: operator= ( class_name && ) = delete;
|
(3) | (начиная с C++11) | |||||||
[править] Объяснение
# Типичное объявление оператора присваивания ход
Original:
# Typical declaration of a move assignment operator
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
# Принудительная оператора ходу назначения, которые будут созданы с помощью компилятора
Original:
# Forcing a move assignment operator to be generated by the compiler
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
# Как избежать неявного назначения ход
Original:
# Avoiding implicit move assignment
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Оператор ход назначения называется всякий раз, когда он выбран по Разрешение перегрузки, например, когда объект появляется на левой стороне выражения присваивания, где правая сторона RValue того же или неявно преобразуются типа.
Original:
The move assignment operator is called whenever it is selected by Разрешение перегрузки, e.g. when an object appears on the left side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Перемещение операторов присваивания обычно "украсть" ресурсы, удерживаемые аргумент (например, указатели на динамически выделяемых объектов, дескрипторов файлов, TCP сокеты, потоки ввода / вывода, выполняемых потоков и т.д.), а не сделать их копии, и оставить аргумент В некоторых действительна, но в противном случае неопределенном состоянии. Например, перемещение назначения из std::string или std::vector оставляет за собой право стороны аргумент пустым.
Original:
Move assignment operators typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc), rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, move-assigning from a std::string or from a std::vector leaves the right-hand side argument empty.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Неявно объявил оператор ход назначения
Если не операторы, определяемые пользователем ход назначения предназначены для классового типа (struct, class, или union), и все из следующих условий:
Original:
If no user-defined move assignment operators are provided for a class type (struct, class, or union), and all of the following is true:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
- нет пользователем объявленный конструктор копииOriginal:there are no user-declared copy constructorsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - нет пользователем объявленных конструкторов ходOriginal:there are no user-declared move constructorsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - нет пользователей заявили операторы копия заданияOriginal:there are no user-declared copy assignment operatorsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - нет пользователем объявленной деструкторовOriginal:there are no user-declared destructorsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - неявно объявлен оператором ход назначения не будут определены как удаленныеOriginal:the implicitly-declared move assignment operator would not be defined as deletedThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
то компилятор будет объявить оператору ход назначение как
inline public членом своего класса с подписью Original:
then the compiler will declare a move assignment operator as an
inline public member of its class with the signature The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Класс может иметь несколько ходу операторов присваивания, например, как T& T::operator=(const T&&) и T& T::operator=(T&&). Если некоторые операторы, определяемые пользователем ход назначения присутствует, пользователь все еще может заставить поколения неявно объявляется оператором ход назначения с ключевым словом
default.Original:
A class can have multiple move assignment operators, e.g. both T& T::operator=(const T&&) and T& T::operator=(T&&). If some user-defined move assignment operators are present, the user may still force the generation of the implicitly declared move assignment operator with the keyword
default.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Потому что некоторые оператор присваивания (перемещение или копирование) всегда объявляется для любого класса, назначение базового класса оператор всегда скрыты. Если использование декларации используется для приведения в операторе присваивания из базового класса, и его аргумент типа может быть такой же, как аргумент типа неявного оператора присвоения производного класса, использование декларации также скрытые неявные Декларация.
Original:
Because some assignment operator (move or copy) is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Удаленные неявно объявлен оператором ход назначения
Неявно объявлен дефолт или оператора ходу назначения для класса
T определяется как' удалены в любом из следующих условий:Original:
The implicitly-declared or defaulted move assignment operator for class
T is defined as deleted in any of the following is true:The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
-
Tимеет не статические данные член, constOriginal:Thas a non-static data member that is constThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Tимеет не статические данные члены ссылочного типа.Original:Thas a non-static data member of a reference type.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Tимеет не статические данные члены, которые не могут двигаться назначенный (удалил, недоступными или неоднозначных оператор присваивания ход)Original:Thas a non-static data member that cannot be move-assigned (has deleted, inaccessible, or ambiguous move assignment operator)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Tимеет прямое или виртуальный базовый класс, который не может двигаться назначенный (удалил, недоступными или неоднозначных оператор присваивания ход)Original:Thas direct or virtual base class that cannot be move-assigned (has deleted, inaccessible, or ambiguous move assignment operator)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Tимеет не статические данные члена или прямой или виртуальной базы без оператора ходу назначения, которые не тривиально копируемой.Original:Thas a non-static data member or a direct or virtual base without a move assignment operator that is not trivially copyable.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Tимеет прямое или косвенное виртуального базового классаOriginal:Thas a direct or indirect virtual base classThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[править] Тривиальные оператор присваивания ход
Неявно объявлен оператором ход назначения для класса
T является тривиальной, если все следующие условия:Original:
The implicitly-declared move assignment operator for class
T is trivial if all of the following is true:The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
-
Tне имеет виртуальных функций-членовOriginal:Thas no virtual member functionsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Tне имеет виртуальные базовые классыOriginal:Thas no virtual base classesThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Оператор ход назначения выбран для каждого прямого базы
TтривиальноOriginal:The move assignment operator selected for every direct base ofTis trivialThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Оператор ход назначения выбран для каждого нестатический тип класса (или массив типа класса) Член КЛУБА
TтривиальноOriginal:The move assignment operator selected for every non-static class type (or array of class type) memeber ofTis trivialThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Тривиальные оператор присваивания ход выполняет те же действия, как тривиальные ОператорПрисваивания копия, которая делает копию объекта представления, как по std::memmove. Все типы данных, совместимые с языком C (POD типов) тривиально двигаться назначаемые.
Original:
A trivial move assignment operator performs the same action as the trivial copy assignmentoperator, that is, makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially move-assignable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Неявно определенный оператор ход назначения
Если неявно объявлен оператором ход назначения не удаляется и не тривиально, оно определено (то есть, тела функции создается и компилируется) компилятором. Для union типа, неявно определен оператор ход присвоение копирует объект представления (как по std::memmove). Для не состоящих в профсоюзе типа класса (class и struct), оператор ход назначения осуществляет полноправный член-мудрый шаг назначение баз объекта и не статическим членам, по их порядка инициализации, с помощью встроенного в задание на скаляры и оператор ход назначения для класса типа.
Original:
If the implicitly-declared move assignment operator is not deleted or trivial, it is defined (that is, a function body is generated and compiled) by the compiler. For union types, the implicitly-defined move assignment operator copies the object representation (as by std::memmove). For non-union class types (class and struct), the move assignment operator performs full member-wise move assignment of the object's bases and non-static members, in their initialization order, using built-in assignment for the scalars and move assignment operator for class types.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Notes
Если обе копии и операторов ход назначения предоставляются, разрешение перегрузки выбирает ход назначения, если аргумент RValue ( или prvalue, таких как безымянные временное или' xvalue таких, как результат std::move ), и выбирает копия задания, если аргумент' именующее (названный объект или функция / оператор возвращения именующее ссылка). Если только копию уступки при условии, все аргументы категории выберите ее (пока она занимает свой аргумент по значению или ссылки на константные, так как rvalues можно привязать к константные ссылки), что делает копию назначения резервной для перемещения назначения, когда двигаться остается недоступным.
Original:
If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either prvalue such as a nameless temporary or xvalue such as the result of std::move), and selects the copy assignment if the argument is lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Копирования и замены оператор присваивания
Original:
The copy-and-swap assignment operator
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
T& T::operator=(T arg) {
swap(arg);
return *this;
}
выполняет эквивалент движения задание на RValue аргументы за счет одного дополнительного вызова ходу конструктор T, которая часто приемлемо.
Original:
performs an equivalent of move assignment for rvalue arguments at the cost of one additional call to the move constructor of T, which is often acceptable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Пример
#include <string> #include <iostream> #include <utility> struct A { std::string s; A() : s("test") {} A(const A& o) : s(o.s) { std::cout << "move failed!\n";} A(A&& o) : s(std::move(o.s)) {} A& operator=(const A&) { std::cout << "copy assigned\n"; return *this; } A& operator=(A&& other) { s = std::move(other.s); std::cout << "move assigned\n"; return *this; } }; A f(A a) { return a; } struct B : A { std::string s2; int n; // implicit move assignment operator B& B::operator=(B&&) // calls A's move assignment operator // calls s2's move assignment operator // and makes a bitwise copy of n }; struct C : B { ~C() {}; // destructor prevents implicit move assignment }; struct D : B { D() {} ~D() {}; // destructor would prevent implicit move assignment D& operator=(D&&) = default; // force a move assignment anyway }; int main() { A a1, a2; std::cout << "Trying to move-assign A from rvalue temporary\n"; a1 = f(A()); // move-assignment from rvalue temporary std::cout << "Trying to move-assign A from xvalue\n"; a2 = std::move(a1); // move-assignment from xvalue std::cout << "Trying to move-assign B\n"; B b1, b2; std::cout << "Before move, b1.s = \"" << b1.s << "\"\n"; b2 = std::move(b1); // calls implicit move assignment std::cout << "After move, b1.s = \"" << b1.s << "\"\n"; std::cout << "Trying to move-assign C\n"; C c1, c2; c2 = std::move(c1); // calls the copy assignment operator std::cout << "Trying to move-assign E\n"; D d1, d2; d2 = std::move(d1); }
Вывод:
Trying to move-assign A from rvalue temporary move assigned Trying to move-assign A from xvalue move assigned Trying to move-assign B Before move, b1.s = "test" move assigned After move, b1.s = "" Trying to move-assign C copy assigned Trying to move-assign E move assigned