You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/cpp/new-operator-cpp.md
+73-53Lines changed: 73 additions & 53 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,68 +1,88 @@
1
1
---
2
-
description: "Learn more about: new Operator (C++)"
3
-
title: "new Operator (C++)"
4
-
ms.date: "11/04/2016"
2
+
description: "Learn more about the grammar and uses of the new operator in C++."
3
+
title: "new operator (C++)"
4
+
ms.date: 11/09/2021
5
5
helpviewer_keywords: ["new keyword [C++]"]
6
6
ms.assetid: 69fee812-1c28-4882-8fda-d1ad17860004
7
7
---
8
-
# new Operator (C++)
8
+
# `new` operator (C++)
9
9
10
-
Allocates memory for an object or array of objects of *type-name* from the free store, commonly called the "heap", and returns a suitably typed, nonzero pointer to the object.
11
-
12
-
> [!NOTE]
13
-
> Microsoft C++ Component Extensions provides support for the **`new`** keyword to add vtable slot entries. For more information, see [new (new slot in vtable)](../extensions/new-new-slot-in-vtable-cpp-component-extensions.md)
10
+
Attempts to allocate and initialize an object or array of objects of a specified or placeholder type, and returns a suitably typed, nonzero pointer to the object (or to the initial object of the array).
14
11
15
12
## Syntax
16
13
17
-
```
18
-
[::] new [placement] new-type-name [new-initializer]
19
-
[::] new [placement] ( type-name ) [new-initializer]
If unsuccessful, **`new`** returns zero or throws an exception; see [The new and delete Operators](../cpp/new-and-delete-operators.md) for more information. You can change this default behavior by writing a custom exception-handling routine and calling the [_set_new_handler](../c-runtime-library/reference/set-new-handler.md) run-time library function with your function name as its argument.
38
+
If unsuccessful, **`new`** returns zero or throws an exception. For more information, see [The `new` and `delete` Operators](../cpp/new-and-delete-operators.md). You can change this default behavior by writing a custom exception-handling routine and calling the [`_set_new_handler`](../c-runtime-library/reference/set-new-handler.md) run-time library function with your function name as its argument.
25
39
26
-
For information on how to create an object on the managed heap, see [gcnew](../extensions/ref-new-gcnew-cpp-component-extensions.md).
40
+
For information on how to create an object on the managed heap in C++/CLI and C++/CX, see [gcnew](../extensions/ref-new-gcnew-cpp-component-extensions.md).
41
+
42
+
> [!NOTE]
43
+
> Microsoft C++ Component Extensions (C++/CX) provides support for the **`new`** keyword to add vtable slot entries. For more information, see [`new` (new slot in vtable)](../extensions/new-new-slot-in-vtable-cpp-component-extensions.md)
27
44
28
45
When **`new`** is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.
29
46
30
-
Use the [delete](../cpp/delete-operator-cpp.md) operator to deallocate the memory allocated with the **`new`** operator.
47
+
Use the [`delete`](../cpp/delete-operator-cpp.md) operator to deallocate the memory allocated by the **`new`** operator. Use the **`delete[]`** operator to delete an array allocated by the **`new`** operator.
31
48
32
-
The following example allocates and then frees a two-dimensional array of characters of size `dim` by 10. When allocating a multidimensional array, all dimensions except the first must be constant expressions that evaluate to positive values; the leftmost array dimension can be any expression that evaluates to a positive value. When allocating an array using the **`new`** operator, the first dimension can be zero — the **`new`** operator returns a unique pointer.
49
+
The following example allocates and then frees a two-dimensional array of characters of size `dim` by 10. When allocating a multidimensional array, all dimensions except the first must be constant expressions that evaluate to positive values. The leftmost array dimension can be any expression that evaluates to a positive value. When allocating an array using the **`new`** operator, the first dimension can be zero; the **`new`** operator returns a unique pointer.
33
50
34
51
```cpp
35
52
char (*pchar)[10] = newchar[dim][10];
36
53
delete [] pchar;
37
54
```
38
55
39
-
The *type-name* cannot contain **`const`**, **`volatile`**, class declarations, or enumeration declarations. Therefore, the following expression is illegal:
56
+
The *`type-id`* can't contain **`const`**, **`volatile`**, class declarations, or enumeration declarations. The following expression is ill-formed:
40
57
41
58
```cpp
42
59
volatilechar *vch = newvolatilechar[20];
43
60
```
44
61
45
-
The **`new`** operator does not allocate reference types because they are not objects.
62
+
The **`new`** operator doesn't allocate reference types because they're not objects.
46
63
47
-
The **`new`** operator cannot be used to allocate a function, but it can be used to allocate pointers to functions. The following example allocates and then frees an array of seven pointers to functions that return integers.
64
+
The **`new`** operator can't be used to allocate a function, but it can be used to allocate pointers to functions. The following example allocates and then frees an array of seven pointers to functions that return integers.
48
65
49
66
```cpp
50
67
int (**p) () = new (int (*[7]) ());
51
68
delete *p;
52
69
```
53
70
54
-
If you use the operator **`new`** without any extra arguments, and compile with the [/GX](../build/reference/gx-enable-exception-handling.md), [/EHa](../build/reference/eh-exception-handling-model.md), or [/EHs](../build/reference/eh-exception-handling-model.md) option, the compiler will generate code to call operator **`delete`** if the constructor throws an exception.
71
+
If you use the operator **`new`** without any extra arguments, and compile with the [`/GX`](../build/reference/gx-enable-exception-handling.md), [`/EHa`](../build/reference/eh-exception-handling-model.md), or [`/EHs`](../build/reference/eh-exception-handling-model.md) option, the compiler generates code to call operator **`delete`** if the constructor throws an exception.
55
72
56
73
The following list describes the grammar elements of **`new`**:
57
74
58
-
*placement*<br/>
59
-
Provides a way of passing additional arguments if you overload **`new`**.
75
+
*`new-placement`*\
76
+
Provides a way of passing extra arguments if you overload **`new`**.
77
+
78
+
*`type-id`*\
79
+
Specifies the type to be allocated; it can be either a built-in or user-defined type. If the type specification is complicated, it can be surrounded by parentheses to force the order of binding. The type may be a placeholder (**`auto`**) whose type is determined by the compiler.
60
80
61
-
*type-name*<br/>
62
-
Specifies type to be allocated; it can be either a built-in or user-defined type. If the type specification is complicated, it can be surrounded by parentheses to force the order of binding.
81
+
*`new-initializer`*\
82
+
Provides a value for the initialized object. Initializers can't be specified for arrays. The **`new`** operator will create arrays of objects only if the class has a default constructor.
63
83
64
-
*initializer*<br/>
65
-
Provides a value for the initialized object. Initializers cannot be specified for arrays. The **`new`** operator will create arrays of objects only if the class has a default constructor.
84
+
*`noptr-new-declarator`*\
85
+
Specifies the bounds of an array. When allocating a multidimensional array, all dimensions except the first must be constant expressions that evaluate to positive values convertible to `std::size_t`. The leftmost array dimension can be any expression that evaluates to a positive value. The *`attribute-specifier-seq`* applies to the associated array type.
66
86
67
87
## Example: Allocate and free a character array
68
88
@@ -111,7 +131,7 @@ int main() {
111
131
112
132
## Example: `new` operator
113
133
114
-
If you use the placement new form of the **`new`** operator, the form with arguments in addition to the size of the allocation, the compiler does not support a placement form of the **`delete`** operator if the constructor throws an exception. For example:
134
+
If you use the placement form of the **`new`** operator (the form with more arguments than the size), the compiler doesn't support a placement form of the **`delete`** operator if the constructor throws an exception. For example:
115
135
116
136
```cpp
117
137
// expre_new_Operator2.cpp
@@ -133,7 +153,7 @@ void F(void) {
133
153
// ::operator delete(void*, char*, int) to deallocate
134
154
// the memory pointed to by pa2. Since
135
155
// ::operator delete(void*, char*, int) has not been implemented,
136
-
// memory will be leaked when the deallocation cannot occur.
156
+
// memory will be leaked when the deallocation can't occur.
137
157
138
158
A* pa2 = new(__FILE__, __LINE__) A(20);
139
159
} catch (...) {
@@ -145,9 +165,9 @@ int main() {
145
165
}
146
166
```
147
167
148
-
## Initializing object allocated with new
168
+
## Initializing objects allocated with `new`
149
169
150
-
An optional *initializer* field is included in the grammar for the **`new`** operator. This allows new objects to be initialized with user-defined constructors. For more information about how initialization is done, see [Initializers](../cpp/initializers.md). The following example illustrates how to use an initialization expression with the **`new`** operator:
170
+
An optional *`new-initializer`* field is included in the grammar for the **`new`** operator. This field allows new objects to be initialized with user-defined constructors. For more information about how initialization is done, see [Initializers](../cpp/initializers.md). The following example illustrates how to use an initialization expression with the **`new`** operator:
In this example, the object `CheckingAcct` is allocated using the **`new`** operator, but no default initialization is specified. Therefore, the default constructor for the class, `Acct()`, is called. Then the object `SavingsAcct` is allocated the same way, except that it is explicitly initialized to 34.98. Because 34.98 is of type **`double`**, the constructor that takes an argument of that type is called to handle the initialization. Finally, the nonclass type `HowMuch` is initialized to 43.0.
194
+
In this example, the object `CheckingAcct` is allocated using the **`new`** operator, but no default initialization is specified. So, the default constructor for the class, `Acct()`, is called. Then the object `SavingsAcct` is allocated the same way, except that it's explicitly initialized to 34.98. Because 34.98 is of type **`double`**, the constructor that takes an argument of that type is called to handle the initialization. Finally, the non-class type `HowMuch` is initialized to 43.0.
175
195
176
196
If an object is of a class type and that class has constructors (as in the preceding example), the object can be initialized by the **`new`** operator only if one of these conditions is met:
177
197
178
-
- The arguments provided in the initializer agree with those of a constructor.
198
+
- The arguments provided in the initializer match the arguments of a constructor.
179
199
180
200
- The class has a default constructor (a constructor that can be called with no arguments).
181
201
182
-
No explicit per-element initialization can be done when allocating arrays using the **`new`** operator; only the default constructor, if present, is called. See [Default Arguments](../cpp/default-arguments.md) for more information.
202
+
Explicit per-element initialization can't be done when allocating arrays using the **`new`** operator; only the default constructor, if present, is called. For more information, see [Default arguments](../cpp/default-arguments.md).
183
203
184
-
If the memory allocation fails (**operator new** returns a value of 0), no initialization is performed. This protects against attempts to initialize data that does not exist.
204
+
If the memory allocation fails (**`operator new`** returns a value of 0), no initialization is done. This behavior protects against attempts to initialize data that doesn't exist.
185
205
186
-
As with function calls, the order in which initialized expressions are evaluated is not defined. Furthermore, you should not rely on these expressions being completely evaluated before the memory allocation is performed. If the memory allocation fails and the **`new`** operator returns zero, some expressions in the initializer may not be completely evaluated.
206
+
As with function calls, the order in which initialized expressions are evaluated isn't defined. Furthermore, you shouldn't rely on these expressions being evaluated completely before the memory allocation takes place. If the memory allocation fails and the **`new`** operator returns zero, some expressions in the initializer may not be evaluated completely.
187
207
188
-
## Lifetime of objects allocated with new
208
+
## Lifetime of objects allocated with `new`
189
209
190
-
Objects allocated with the **`new`** operator are not destroyed when the scope in which they are defined is exited. Because the **`new`** operator returns a pointer to the objects it allocates, the program must define a pointer with suitable scope to access those objects. For example:
210
+
Objects allocated with the **`new`** operator aren't destroyed when the scope in which they're defined is exited. Because the **`new`** operator returns a pointer to the objects it allocates, the program must define a pointer with suitable scope to access and delete those objects. For example:
Once the pointer `AnotherArray` goes out of scope in the example, the object can no longer be deleted.
216
236
217
-
## How new works
237
+
## How `new` works
218
238
219
-
The *allocation-expression* — the expression containing the **`new`** operator — does three things:
239
+
The *`new-expression`* (the expression containing the **`new`** operator) does three things:
220
240
221
-
- Locates and reserves storage for the object or objects to be allocated. When this stage is complete, the correct amount of storage is allocated, but it is not yet an object.
241
+
- Locates and reserves storage for the object or objects to be allocated. When this stage is complete, the correct amount of storage is allocated, but it's not yet an object.
222
242
223
243
- Initializes the object(s). Once initialization is complete, enough information is present for the allocated storage to be an object.
224
244
225
-
- Returns a pointer to the object(s) of a pointer type derived from *new-type-name* or *type-name*. The program uses this pointer to access the newly allocated object.
245
+
- Returns a pointer to the object(s) of a pointer type derived from *`new-type-id`* or *`type-id`*. The program uses this pointer to access the newly allocated object.
226
246
227
-
The **`new`** operator invokes the function **operator new**. For arrays of any type, and for objects that are not of **`class`**, **`struct`**, or **`union`** types, a global function, **::operator new**, is called to allocate storage. Class-type objects can define their own **operator new** static member function on a per-class basis.
247
+
The **`new`** operator invokes the function **`operator new`**. For arrays of any type, and for objects that aren't **`class`**, **`struct`**, or **`union`** types, a global function, **`::operator new`**, is called to allocate storage. Class-type objects can define their own **`operator new`** static member function on a per-class basis.
228
248
229
-
When the compiler encounters the **`new`** operator to allocate an object of type **type**, it issues a call to `type`**::operator new( sizeof(**`type`**) )** or, if no user-defined **operator new** is defined, **::operator new( sizeof(**`type`**) )**. Therefore, the **`new`** operator can allocate the correct amount of memory for the object.
249
+
When the compiler encounters the **`new`** operator to allocate an object of type `T`, it issues a call to `T::operator new( sizeof(T) )` or, if no user-defined **`operator new`** is defined, `::operator new( sizeof(T) )`. It's how the **`new`** operator can allocate the correct amount of memory for the object.
230
250
231
251
> [!NOTE]
232
-
> The argument to **operatornew** is of type `size_t`. This type is defined in \<direct.h>, \<malloc.h>, \<memory.h>, \<search.h>, \<stddef.h>, \<stdio.h>, \<stdlib.h>, \<string.h>, and \<time.h>.
252
+
> The argument to **`operatornew`** is of type `std::size_t`. This type is defined in \<direct.h>, \<malloc.h>, \<memory.h>, \<search.h>, \<stddef.h>, \<stdio.h>, \<stdlib.h>, \<string.h>, and \<time.h>.
233
253
234
-
An option in the grammar allows specification of *placement* (see the Grammar for [new Operator](../cpp/new-operator-cpp.md)). The *placement* parameter can be used only for user-defined implementations of **operatornew**; it allows extra information to be passed to **operatornew**. An expression with a *placement* field such as `T *TObject = new ( 0x0040 ) T;` is translated to `T *TObject = T::operatornew( sizeof( T ), 0x0040 );` ifclassT has member operator new, otherwise to `T *TObject = ::operator new( sizeof( T ), 0x0040 );`.
254
+
An option in the grammar allows specification of *`new-placement`* (see the Grammar for [`new` Operator](../cpp/new-operator-cpp.md)). The *`new-placement`* parameter can be used only for user-defined implementations of **`operatornew`**; it allows extra information to be passed to **`operatornew`**. An expression with a *`new-placement`* field such as `T *TObject = new ( 0x0040 ) T;` is translated to `T *TObject = T::operatornew( sizeof( T ), 0x0040 );` ifclassT has member `operator new`, otherwise to `T *TObject = ::operator new( sizeof( T ), 0x0040 );`.
235
255
236
-
The original intention of the *placement* field was to allow hardware-dependent objects to be allocated at user-specified addresses.
256
+
The original intention of the *`new-placement`* field was to allow hardware-dependent objects to be allocated at user-specified addresses.
237
257
238
258
> [!NOTE]
239
-
> Although the preceding example shows only one argument in the *placement* field, there is no restriction on how many extra arguments can be passed to **operatornew** this way.
259
+
> Although the preceding example shows only one argument in the *`new-placement`* field, there's no restriction on how many extra arguments can be passed to **`operator new`** this way.
240
260
241
-
Even when **operatornew** has been definedfor a classtype, the global operator can be used by using the form of this example:
261
+
Even when **`operator new`** has been defined for a class type `T`, you can use the global operator **`new`** explicitly, as in this example:
242
262
243
263
```cpp
244
-
T *TObject =::new TObject;
264
+
T *TObject =::new TObject;
245
265
```
246
266
247
267
The scope-resolution operator (`::`) forces use of the global **`new`** operator.
248
268
249
269
## See also
250
270
251
-
[Expressions with Unary Operators](../cpp/expressions-with-unary-operators.md)<br/>
0 commit comments