Copy constructors
Материал из 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 не является шаблоном конструктор, первый параметр T&, const T&, volatile T&, или const volatile T&, и либо не существует никаких других параметров, или остальные параметры имеют значения по умолчанию. Типа с общественностью конструктор копии CopyConstructible.Original:
A copy constructor of class
T is a non-template constructor whose first parameter is T&, const T&, volatile T&, or const volatile T&, and either there are no other parameters, or the rest of the parameters all have default values. A type with a public copy constructor is CopyConstructible.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 ( const class_name & )
|
(1) | ||||||||
class_name ( const class_name & ) = default;
|
(1) | ||||||||
class_name ( const class_name & ) = delete;
|
(1) | ||||||||
[править] Объяснение
# Типичное объявление конструктора копии
Original:
# Typical declaration of a 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.
# Принудительная конструктора копии, которые будут созданы с помощью компилятора
Original:
# Forcing a copy constructor 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 default 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.
Конструктор копирования вызывается при инициализации объекта из другого объекта того же типа, который включает в себя
Original:
The copy constructor is called whenever an object is initialized from another object of the same type, which includes
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 a = b; или T a(b);, где Ь типа
TOriginal:initialization, T a = b; or T a(b);, where b is of typeTThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - проходящий аргумент функции: f(a);, где
aимеет типTиfявляется void f(T t)Original:function argument passing: f(a);, whereais of typeTandfis void f(T t)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Функция возврата: return a; внутри функции, такие как T f(), где
aимеет типT, который не имеет ход конструктор.Original:function return: return a; inside a function such as T f(), whereais of typeT, which has no move constructor.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[править] Неявно объявлен конструктор копии
Если нет пользовательского конструктора копии предназначены для классового типа (struct, class, или union), компилятор всегда будет объявить конструктор копий, как
inline public членом своего класса. Это неявно объявлен конструктор копирования имеет вид T::T(const T&), если все следующие условия:Original:
If no user-defined copy constructors are provided for a class type (struct, class, or union), the compiler will always declare a copy constructor as an
inline public member of its class. This implicitly-declared copy constructor has the form T::T(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.
- всех прямых и виртуальных баз
Tимеют конструкторы копирования со ссылкой на конструкции или конструкции летучих в качестве первого параметраOriginal:all direct and virtual bases ofThave copy constructors with references to const or to const volatile as their first parametersThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - все не статические члены
Tимеют конструкторы копирования со ссылкой на конструкции или конструкции летучих в качестве первого параметраOriginal:all non-static members ofThave copy constructors with references to const or to const volatile as their first parametersThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
В противном случае, неявно объявлен конструктор копирования T::T(T&). (Обратите внимание, что в связи с этими правилами, неявно объявлен конструктор копирования не может связываться с летучими аргумент именующее)
Original:
Otherwise, the implicitly-declared copy constructor is T::T(T&). (Note that due to these rules, the implicitly-declared copy constructor 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(const T&) и T::T(T&). Если некоторые пользовательские конструкторы копии присутствует, пользователь все еще может заставить поколения неявно объявляется конструктор копии с ключевым словом
default (начиная с C++11).Original:
A class can have multiple copy constructors, e.g. both T::T(const T&) and T::T(T&). If some user-defined copy constructors are present, the user may still force the generation of the implicitly declared copy constructor with the keyword
default (начиная с C++11).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 не определено (до C++11) / определяется как' удалены (начиная с C++11) в любом из следующих условий:Original:
The implicitly-declared or defaulted copy constructor for class
T is undefined (до C++11) / defined as deleted (начиная с C++11) 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имеет не статические данные пользователей, которые не могут быть скопированы (были удалены, недоступными или неоднозначных конструкторов копии)Original:Thas non-static data members that cannot be copied (have deleted, inaccessible, or ambiguous copy constructors)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 copied (has deleted, inaccessible, or ambiguous copy constructors)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 with a deleted or inaccessible destructorThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Tимеет определенный пользователем конструктор движение или перемещение оператор присваивания (начиная с C++11)Original:Thas a user-defined move constructor or move assignment operator (начиная с C++11)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Tявляется объединением и имеет вариант член с нетривиальным (начиная с C++11) конструктор копированияOriginal:Tis a union and has a variant member with non-trivial copy constructor (начиная с C++11)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Tесть данные членов RValue (начиная с C++11) типOriginal:Thas a data member of rvalue reference type (начиная с C++11)The 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 constructor 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 constructor 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 constructor 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 constructor is a constructor that creates a bytewise copy of the object representation of the argument, and performs no other action. Objects with trivial copy constructors can be copied by copying their object representations manually, e.g. with std::memmove. All data types compatible with the C language (POD types) are trivially copyable.
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 constructor 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 constructor copies the object representation (as by std::memmove). For non-union class types (class and struct), the constructor performs full member-wise copy of the object's bases and non-static members, in their initialization order, using direct initialization.
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 constructor is deprecated(начиная с C++11) if
T has a user-defined destructor or user-defined 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.
You can help to correct and verify the translation. Click here for instructions.
[править] Notes
Во многих ситуациях, конструкторы копирования оптимизированы, даже если они будут производить наблюдаемые побочные эффекты, см. Копия элизии
Original:
In many situations, copy constructors are optimized out even if they would produce observable side-effects, see Копия элизии
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 A { int n; A(int n=1) : n(n) {} A(const A& a) : n(a.n) {} // user-defined copy ctor }; struct B : A { // implicit default ctor B::B() // implicit copy ctor B::B(const B&) }; struct C : B { C() : B() {} private: C(const C&); // non-copiable, C++98 style }; int main() { A a1(7); A a2(a1); // calls the copy ctor B b; B b2 = b; A a3 = b; // conversion to A& and copy ctor volatile A va(10); // A a4 = va; // compile error C c; // C c2 = c; // compile error }