Copy 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, T&, const T&, volatile T&, или const volatile T&. Типа с общественностью оператор присваивания копии CopyAssignable.Original:
A copy 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, T&, const T&, volatile T&, or const volatile T&. A type with a public copy assignment operator is CopyAssignable.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= ( const class_name & )
|
(2) | (начиная с C++11) | |||||||
class_name & class_name :: operator= ( const class_name & ) = default;
|
(3) | (начиная с C++11) | |||||||
class_name & class_name :: operator= ( const class_name & ) = delete;
|
(4) | (начиная с C++11) | |||||||
[править] Объяснение
# Типичное объявление оператор присваивания копии при copy-and-swap idiom могут быть использованы
Original:
# Typical declaration of a copy assignment operator when copy-and-swap idiom can be used
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:
# Typical declaration of a copy assignment operator when copy-and-swap idiom cannot be used
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 copy 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 copy 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.
Оператор копирующего присваивания вызывается, когда выбран Разрешение перегрузки, например, когда объект появляется на левой стороне выражения присваивания.
Original:
The copy assignment operator is called whenever selected by Разрешение перегрузки, e.g. when an object appears on the left side of an assignment expression.
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), компилятор всегда будет заявлять о качестве встроенного открытый член класса. Это неявно объявлен копирования оператора присваивания имеет вид T& T::operator=(const T&), если все следующие условия:
Original:
If no user-defined copy assignment operators are provided for a class type (struct, class, or union), the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form T& T::operator=(const T&) 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.
- каждая прямая базы
BизTимеет копирования оператора присваивания, параметры которогоBилиconst B&или const volatile B&Original:each direct baseBofThas a copy assignment operator whose parameters areBorconst B&or const volatile B&The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - каждый не статические данные члены
MизTтипа класса или массив типа класса имеет копирования оператора присваивания, параметры которогоMилиconst M&или const volatile M&Original:each non-static data memberMofTof class type or array of class type has a copy assignment operator whose parameters areMorconst M&or const volatile M&The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
В противном случае неявно объявлен копирования оператора присваивания объявлен как T& T::operator=(T&). (Обратите внимание, что в связи с этими правилами, неявно объявлен копирования оператора присваивания не может связываться с летучими аргумент именующее)
Original:
Otherwise the implicitly-declared copy assignment operator is declared as T& T::operator=(T&). (Note that due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument)
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 copy assignment operators, e.g. both T& T::operator=(const T&) and T& T::operator=(T). If some user-defined copy assignment operators are present, the user may still force the generation of the implicitly declared copy 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 the copy assignment operator 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 copy 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 copy-assigned (has deleted, inaccessible, or ambiguous copy 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 copy-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 user-declared move constructorThe 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 user-declared move assignment operatorThe 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 copy 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 copy 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 copy 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 copy assignment operator makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially copy-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 copy 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 copy assignment copies the object representation (as by std::memmove). For non-union class types (class and struct), the operator performs member-wise copy assignment of the object's bases and non-static members, in their initialization order, using, using built-in assignment for the scalars and copy 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.
Поколения неявно определен оператор присваивания копии deprecated(начиная с C++11) если
T имеет интуитивно заявил деструктора или пользовательский объявлен конструктор копирования.Original:
The generation of the implicitly-defined copy assignment operator is deprecated(начиная с C++11) if
T has a user-declared destructor or user-declared copy constructor.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:
Copy assignment operator can be expressed in terms of copy constructor, destructor, and the swap() member function, if one is provided:
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) { // copy/move constructor is called to construct arg
swap(arg); // resources exchanged between *this and arg
return *this;
} // destructor is called to release the resources formerly held by *this
Для не-метание своп (), эта форма обеспечивает сильная гарантия исключения. Для RValue аргументов, эта форма автоматически вызывает движение конструктор, а иногда называют «объединяющей оператор присваивания" (как в, как копирование и перемещение).
Original:
For non-throwing swap(), this form provides сильная гарантия исключения. For rvalue arguments, this form automatically invokes the move constructor, and is sometimes referred to as "unifying assignment operator" (as in, both copy and move).
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 <iostream> #include <memory> struct A { int n; std::string s1; // user-defined copy assignment, copy-and-swap form A& operator=(A other) { std::cout << "copy assignment of A\n"; std::swap(n, other.n); std::swap(s1, other.s1); return *this; } }; struct B : A { std::string s2; // implicitly-defined copy assignment }; struct C { std::unique_ptr<int[]> data; std::size_t size; // non-copy-and-swap assignment C& operator=(const C& other) { // check for self-assignment if(&other == this) return *this; // reuse storage when possible if(size != other.size) data.reset(new int[other.size]); std::copy(&other.data[0], &other.data[0] + std::min(size, other.size), &data[0]); return *this; } // note: copy-and-swap would always cause a reallocation }; int main() { A a1, a2; std::cout << "a1 = a2 calls "; a1 = a2; // user-defined copy assignment B b1, b2; b2.s1 = "foo"; b2.s2 = "bar"; std::cout << "b1 = b2 calls "; b1 = b2; // implicitly-defined copy assignment std::cout << "b1.s1 = " << b1.s1 << " b1.s2 = " << b1.s2 << '\n'; }
Вывод:
a1 = a2 calls copy assignment of A b1 = b2 calls copy assignment of A b1.s1 = foo b1.s2 = bar