Skip to content

Commit dc3ec27

Browse files
author
Colin Robertson
authored
Address issues in recent PRs (#3898)
* Address issues in recent PRs * Add C26826 to TOC * Test indent * Remove block format test
1 parent 24fc417 commit dc3ec27

5 files changed

Lines changed: 96 additions & 73 deletions

File tree

docs/code-quality/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,8 @@ items:
579579
href: ../code-quality/c26810.md
580580
- name: C26811
581581
href: ../code-quality/c26811.md
582+
- name: C26826
583+
href: ../code-quality/c26826.md
582584
- name: C28020
583585
href: ../code-quality/c28020.md
584586
- name: C28021

docs/cpp/new-operator-cpp.md

Lines changed: 73 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,88 @@
11
---
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
55
helpviewer_keywords: ["new keyword [C++]"]
66
ms.assetid: 69fee812-1c28-4882-8fda-d1ad17860004
77
---
8-
# new Operator (C++)
8+
# `new` operator (C++)
99

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).
1411

1512
## Syntax
1613

17-
```
18-
[::] new [placement] new-type-name [new-initializer]
19-
[::] new [placement] ( type-name ) [new-initializer]
20-
```
14+
*`new-expression`*:\
15+
&emsp; **`::`**<sub>opt</sub> **`new`** *`new-placement`*<sub>opt</sub> *`new-type-id`* *`new-initializer`*<sub>opt</sub>\
16+
&emsp; **`::`**<sub>opt</sub> **`new`** *`new-placement`*<sub>opt</sub> **`(`** *`type-id`* **`)`** *`new-initializer`*<sub>opt</sub>
17+
18+
*`new-placement`*:\
19+
&emsp; **`(`** *`expression-list`* **`)`**
20+
21+
*`new-type-id`*:\
22+
&emsp; *`type-specifier-seq`* *`new-declarator`*<sub>opt</sub>
23+
24+
*`new-declarator`*:\
25+
&emsp; *`ptr-operator`* *`new-declarator`*<sub>opt</sub>\
26+
&emsp; *`noptr-new-declarator`*
27+
28+
*`noptr-new-declarator`*:\
29+
&emsp; **`[`** *`expression`* **`]`** *`attribute-specifier-seq`*<sub>opt</sub>\
30+
&emsp; *`noptr-new-declarator`* **`[`** *`constant-expression`* **`]`** *`attribute-specifier-seq`*<sub>opt</sub>
31+
32+
*`new-initializer`*:\
33+
&emsp; **`(`** *`expression-list`*<sub>opt</sub> **`)`**\
34+
&emsp; *`braced-init-list`*
2135

2236
## Remarks
2337

24-
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.
2539

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)
2744
2845
When **`new`** is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.
2946

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.
3148

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.
3350

3451
```cpp
3552
char (*pchar)[10] = new char[dim][10];
3653
delete [] pchar;
3754
```
3855

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:
4057

4158
```cpp
4259
volatile char *vch = new volatile char[20];
4360
```
4461

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.
4663

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.
4865

4966
```cpp
5067
int (**p) () = new (int (*[7]) ());
5168
delete *p;
5269
```
5370

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.
5572

5673
The following list describes the grammar elements of **`new`**:
5774

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.
6080

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.
6383

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.
6686

6787
## Example: Allocate and free a character array
6888

@@ -111,7 +131,7 @@ int main() {
111131
112132
## Example: `new` operator
113133
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:
115135
116136
```cpp
117137
// expre_new_Operator2.cpp
@@ -133,7 +153,7 @@ void F(void) {
133153
// ::operator delete(void*, char*, int) to deallocate
134154
// the memory pointed to by pa2. Since
135155
// ::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.
137157
138158
A* pa2 = new(__FILE__, __LINE__) A(20);
139159
} catch (...) {
@@ -145,9 +165,9 @@ int main() {
145165
}
146166
```
147167

148-
## Initializing object allocated with new
168+
## Initializing objects allocated with `new`
149169

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:
151171

152172
```cpp
153173
// expre_Initializing_Objects_Allocated_with_new.cpp
@@ -166,28 +186,28 @@ int main()
166186
{
167187
Acct *CheckingAcct = new Acct;
168188
Acct *SavingsAcct = new Acct ( 34.98 );
169-
double *HowMuch = new double ( 43.0 );
189+
double *HowMuch = new double { 43.0 };
170190
// ...
171191
}
172192
```
173193

174-
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.
175195

176196
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:
177197

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.
179199

180200
- The class has a default constructor (a constructor that can be called with no arguments).
181201

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).
183203

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.
185205

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.
187207

188-
## Lifetime of objects allocated with new
208+
## Lifetime of objects allocated with `new`
189209

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:
191211

192212
```cpp
193213
// expre_Lifetime_of_Objects_Allocated_with_new.cpp
@@ -214,40 +234,40 @@ int main()
214234

215235
Once the pointer `AnotherArray` goes out of scope in the example, the object can no longer be deleted.
216236

217-
## How new works
237+
## How `new` works
218238

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:
220240

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.
222242

223243
- Initializes the object(s). Once initialization is complete, enough information is present for the allocated storage to be an object.
224244

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.
226246

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.
228248

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.
230250

231251
> [!NOTE]
232-
> The argument to **operator new** 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 **`operator new`** 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>.
233253

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 **operator new**; it allows extra information to be passed to **operator new**. An expression with a *placement* field such as `T *TObject = new ( 0x0040 ) T;` is translated to `T *TObject = T::operator new( sizeof( T ), 0x0040 );` if class T 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 **`operator new`**; it allows extra information to be passed to **`operator new`**. An expression with a *`new-placement`* field such as `T *TObject = new ( 0x0040 ) T;` is translated to `T *TObject = T::operator new( sizeof( T ), 0x0040 );` if class T has member `operator new`, otherwise to `T *TObject = ::operator new( sizeof( T ), 0x0040 );`.
235255

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.
237257

238258
> [!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 **operator new** 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.
240260
241-
Even when **operator new** has been defined for a class type, 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:
242262
243263
```cpp
244-
T *TObject =::new TObject;
264+
T *TObject = ::new TObject;
245265
```
246266
247267
The scope-resolution operator (`::`) forces use of the global **`new`** operator.
248268
249269
## See also
250270
251-
[Expressions with Unary Operators](../cpp/expressions-with-unary-operators.md)<br/>
252-
[Keywords](../cpp/keywords-cpp.md)<br/>
253-
[new and delete operators](../cpp/new-and-delete-operators.md)
271+
[Expressions with unary operators](../cpp/expressions-with-unary-operators.md)\
272+
[Keywords](../cpp/keywords-cpp.md)\
273+
[`new` and `delete` operators](../cpp/new-and-delete-operators.md)

0 commit comments

Comments
 (0)