copy initialization
Материал из 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. |
Инициализирует объект из другого объекта
Original:
Initializes an object from another object
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 object = other ;
|
(1) | ||||||||
f(other);
|
(2) | ||||||||
return other;
|
(3) | ||||||||
catch ( T other) ;
|
(4) | ||||||||
T array [ N ] = { other };
|
(5) | ||||||||
[править] Объяснение
Копировать инициализация выполняется в следующих ситуациях:
Original:
Copy initialization is performed in the following situations:
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.
1)
При именем переменной (автоматические, статические, или поток-местный) объявляется с помощью инициализатора, состоящая из знака равенства, за которым следует выражение.
Original:
when a named variable (automatic, static, or thread-local) is declared with the initializer consisting of an equals sign followed by an 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.
2)
при переходе аргумента функции по значению
Original:
when passing an argument to a function by value
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.
3)
при возвращении из функции, которая возвращает по значению
Original:
when returning from a function that returns by value
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.
4)
при ловле исключения по значению
Original:
when catching an exception by value
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.
5)
как часть совокупный инициализации, для инициализации каждого элемента, для которого инициализатор предоставляется
Original:
as part of совокупный инициализации, to initialize each element for which an initializer 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.
Последствия копию инициализации являются:
Original:
The effects of copy initialization are:
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является одним классом и типом other в CV-неквалифицированным версияTили класса, производного отT, конструкторыTрассматриваются и лучший матч выбирается разрешение перегрузки. Конструктор затем вызывается для инициализации объекта.Original:IfTis a class type and the type of other is cv-unqualified version ofTor a class derived fromT, the constructors ofTare examined and the best match is selected by overload resolution. The constructor is then called to initialize the object.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Если
Tэто класс, тип, и тип other разные, или еслиTне является классом типа, но тип other это класс, пользовательского преобразования последовательностей, который может конвертировать от типа other вTрассматриваются и лучшее выбран один через разрешение перегрузки. Результат преобразования, которая является prvalue временного назначения типа, который затем используется для Прямая инициализации объекта. На последнем этапе, как правило, устранены и результат функции преобразования построена непосредственно в памяти, выделенной для целевой объект, но конструктор копии должны быть доступны даже если он не используется.Original:IfTis a class type, and the type of other is different, or ifTis non-class type, but the type of other is a class type, пользовательского преобразования последовательностей that can convert from the type of other toTare examined and the best one is selected through overload resolution. The result of the conversion, which is a prvalue temporary of the destination type, is then used to Прямая инициализации the object. The last step is usually устранены and the result of the conversion function is constructed directly in the memory allocated for the target object, but the copy constructor is required to be accessible even though it's not used.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- В противном случае (если ни
T, ни тип other относятся к классу типов), стандартные преобразования используется, если необходимо, чтобы преобразовать значение other к CV-неквалифицированным версияT.Original:Otherwise (if neitherTnor the type of other are class types), стандартные преобразования are used, if necessary, to convert the value of other to the cv-unqualified version ofT.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[править] Notes
Копировать инициализации меньше прав, чем прямая инициализация: копия инициализации рассматривает только без явных конструкторов и определяемые пользователем функции преобразования.
Original:
Copy-initialization is less permissive than direct-initialization: copy-initialization only considers non-explicit constructors and user-defined conversion functions.
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.
Если other является RValue выражения, двигаться конструктор будет выбран разрешение перегрузки и призвали во время копирования инициализации.
Original:
If other is an rvalue expression, двигаться конструктор will be selected by overload resolution and called during copy-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.
Знак равенства,
=, в копии инициализация имени переменной не связано с оператором присваивания. Перегрузки оператора присваивания не влияет на копию инициализации.Original:
The equals sign,
=, in copy-initialization of a named variable is not related to the assignment operator. Assignment operator overloads have no effect on copy-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.
[править] Пример
#include <string> #include <utility> #include <memory> int main() { std::string s = "test"; // OK: constructor is non-explicit std::string s2 = std::move(s); // this copy-initialization performs a move // std::unique_ptr<int> p = new int(1); // error: constructor is explicit std::unique_ptr<int> p(new int(1)); // OK: direct-initialization int n = 3.14; // floating-integral conversion const int b = n; // const doesn't matter int c = b; // ...either way }