value 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:
Provides the default initial value to a new 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 {};
|
(1) | (начиная с C++11) | |||||||
T();
T |
(2) | (начиная с C++11) | |||||||
new T ();
|
(3) | (начиная с C++11) | |||||||
[править] Объяснение
Значение инициализации осуществляется в трех ситуациях:
Original:
Value initialization is performed in three 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)
При именем переменной (автоматические, статические, или поток-местный) объявляется с помощью инициализатора, состоящий из пары фигурных скобок. (начиная с C++11)
Original:
when a named variable (automatic, static, or thread-local) is declared with the initializer consisting of a pair of braces. (начиная с 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.
2)
При безымянных временный объект создается с инициализатор, состоящий из пустых пару круглые или фигурные скобки.
Original:
when a nameless temporary object is created with the initializer consisting of an empty pair of parentheses or braces.
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 an object with dynamic storage duration is created by a new-expression with the initializer consisting of an empty pair of parentheses or braces.
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 value 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это класс крайней мере с одним пользователем при условии, конструктор любого рода, конструктор по умолчанию называется.Original:IfTis a class type with at least one user-provided constructor of any kind, the конструктор по умолчанию is called.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Если
Tэто не состоящих в профсоюзе типа класса без предоставленные пользователем конструкторов, то объект нулю инициализирован, а затем неявно объявлен вызывается конструктор по умолчанию (если это не тривиально)Original:IfTis an non-union class type without any user-provided constructors, then the object is нулю инициализирован and then the implicitly-declared default constructor is called (unless it's trivial)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Если
Tявляется типом массива, каждый элемент массива является значение инициализацииOriginal:IfTis an array type, each element of the array is value-initializedThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- В противном случае, объект равен нулю инициализирован.Original:Otherwise, the object is zero-initialized.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[править] Notes
Синтаксис T object(); не инициализирует объект, он заявляет, что функция не принимает аргументов и возвращает
T. Путь к значению инициализации переменной перед именем C + +11 была T object = T();, значение которого инициализирует временный, а затем копирования инициализирует объект: большинство компиляторов оптимизации из копии в данном случае.Original:
The syntax T object(); does not initialize an object; it declares a function that takes no arguments and returns
T. The way to value-initialize a named variable before C++11 was T object = T();, which value-initializes a temporary and then copy-initializes the object: most compilers optimize out the copy in this case.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:
References cannot be value-initialized.
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.
Все стандартные контейнеры (std::vector, std::list, и т.д.) стоимость инициализации их элементов, когда построена с одним аргументом
size_type или когда выросла на вызов resize().Original:
All standard containers (std::vector, std::list, etc) value-initialize their elements when constructed with a single
size_type argument or when grown by a call to resize().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 <vector> #include <iostream> struct T1 { int mem1; std::string mem2; }; // no constructors struct T2 { int mem1; std::string mem2; T2(const T2&) {} // a constructor, but no default }; struct T3 { int mem1; std::string mem2; T3() {} // user-provided default ctor }; std::string s{}; // calls default ctor, the value is "" (empty string) int main() { int n{}; // non-class value-initialization, value is 0 double f = double(); // non-class value-init, value is 0.0 int* a = new int[10](); // array of 10 zeroes T1 t1{}; // no ctors: zero-initialized // t1.mem1 is zero-initialized // t1.mem2 is default-initialized // T2 t2{}; // error: has a ctor, but no default ctor T3 t3{}; // user-defined default ctor: // t3.mem1 is default-initialized (the value is indeterminate) // t3.mem2 is default-initialized std::vector<int> v(3); // value-initializes three ints std::cout << s.size() << ' ' << n << ' ' << f << ' ' << a[9] << ' ' << v[2] << '\n'; std::cout << t1.mem1 << ' ' << t3.mem1 << '\n'; delete[] a; }
Вывод:
0 0 0 0 0 0 4199376