new expression
Материал из 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 objects in dynamically obtained memory.
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:
Used where data need to be allocated dynamically, that is, without knowing its size prior the compilation.
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.
Содержание |
[править] Синтаксис
::(необязательно)
|
new
|
type | [array_n](необязательно)
|
(init_params)(необязательно)
|
(1) | ||||
::(необязательно)
|
new
|
(type )
|
[array_n](необязательно)
|
(init_params)(необязательно)
|
(2) | ||||
::(необязательно)
|
new
|
(placement_params)
|
type | [array_n](необязательно)
|
(init_params)(необязательно)
|
(3) | |||
::(необязательно)
|
new
|
(placement_params)
|
(type )
|
[array_n](необязательно)
|
(init_params)(необязательно)
|
(4) | |||
Все версии возвращают объект типа' 'типа *.
Original:
All versions return an object of type 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.
[править] Объяснение
new выражение выделяет область памяти, либо инициализирует один объект или массив объектов там, и возвращает указатель на первый построенный объект. Так как это не иначе можно назвать явного вызова конструктора, выражение это единственный способ построить объект динамически.Original:
The
new expression allocates a memory area, initializes either single object, or an array of objects there and returns a pointer to the first constructed object. Since it is not otherwise possible to call explicitly call a constructor, the expression is the only way to construct an object dynamically.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 first two and last two versions of the expression differ only syntactically. The behavior is the same.
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.
| Этот раздел не завершён Причина: Explanation about how types are specified is missing |
[править] Выделение памяти
Память выделяется по Распределение функций, либо operator new или operator new[].
Original:
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.
В последних двух версиях выражение называется' 'размещению новых и используется для передачи дополнительных параметров (placement_params) к распределению функций.
Original:
The last two versions of the expression are called placement new and are used to pass additional parameters (placement_params) to the allocation function.
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.
Если array_n отсутствует, память выделяется для одного объекта, ссылаясь на operator new распределения функций. В противном случае память для массива из array_n объекты выделяются по телефону operator new[] распределения функций. Отметим, что более чем
size_of( type ) * array_n могут быть выделены из-за дополнительных информации, закодированной компилятором (например, размер массива, так как эта информация необходима для того, чтобы уничтожить объекты в массиве правильно).Original:
If array_n is absent, memory is allocated for a single object by invoking operator new allocation function. Otherwise memory for an array of array_n objects is allocated by calling operator new[] allocation function. Note, that more than
size_of( type ) * array_n might be allocated because of additional information encoded by the compiler (such as the size of the array, since this information is needed in order to destruct the objects in the array properly).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.
Название распределение функцией, во-первых посмотрел в местной класса типа масштабы и только если поиск неудачен, глобальное пространство имен посмотрел вверх. Если
:: присутствует в new выражения, только глобальное пространство имен посмотрел вверх. Прототип функции должно выглядеть следующим образом для того, чтобы распределение функций должны быть выбраны Original:
The allocation function's name is firstly looked up in the local class type scope and only if the lookup fails, the global namespace is looked up. If
:: is present in the new expression, only the global namespace is looked up. The prototype of the function should look like the following in order to the allocation function to be selected: 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.
| void* operator new (size_t count); |
for versions 1, 2, array_n is not present | |
| void* operator new[](size_t count); |
for versions 1, 2, array_n is present | |
| void* operator new (size_t count/*, placement_params...*/); |
for versions 3, 4 (placement new), array_n is not present | |
| void* operator new[](size_t count/*, placement_params...*/); |
for versions 3, 4 (placement new), array_n is present | |
count это количество байт для распределения, placement_params являются параметры, приведенные на размещение новое выражение.Original:
count is number of bytes to allocate, placement_params are the parameters given to the placement new 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.
[править] По умолчанию реализации и перегрузки
Некоторые функции распределения по умолчанию неявно объявленный в каждой единице трансляции. Кроме того, неявные реализаций, предоставляемых компилятором по умолчанию, если программа явно реализовали их. Эти функции следующим образом (см. это для получения дополнительной информации)
Original:
Several default allocation functions are implicitly declared in each translation unit. Also, implicit implementations are provided by the compiler by default, unless the program has explicitly implemented them. These functions are as follows (see это for more information):
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.
| void* operator new (size_t); |
(1) | |
| void* operator new[](size_t); |
(2) | |
| void* operator new (size_t, std::nothrow_t); |
(3) | |
| void* operator new[](size_t, std::nothrow_t); |
(4) | |
| void* operator new (size_t, void* ptr); |
(5) | |
| void* operator new[](size_t, void* ptr); |
(6) | |
выделяет необходимое число байтов или бросает std::bad_alloc на провал
3-4) Original:
allocates requested number of bytes or throws std::bad_alloc on failure
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.
выделяет запрошенное количество байт или возвращает NULL на провал
5-6) Original:
allocates requested number of bytes or returns NULL on failure
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.
возвращается
ptr. Это позволяет построить объект в пользователем область памяти. Программа не должна определить явные реализации этих функций.Original:
returns
ptr. This allows to construct an object in user-supplied memory area. The program must not define explicit implementations for these 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.
[править] Инициализация объекта
Если array_n отсутствует, один объект инициализируется в приобретенной области памяти, передавая init_params в качестве параметров конструктора или вызова конструктора по умолчанию, если их нет.
Original:
If array_n is absent, single object is initialized in the acquired memory area, passing init_params as parameters to the constructor or invoking default constructor if they are not present.
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.
Если array_n присутствует, массив array_n объекты инициализируются, проходя init_params в качестве параметров в конструктор каждого объекта или вызова конструктора по умолчанию, если init_params нет.
Original:
If array_n is present, an array of array_n objects is initialized, passing init_params as parameters to the constructor of each object or invoking default constructor if init_params are not present.
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.