Skip to content

Commit 54bd820

Browse files
committed
[spec] Document NewExpression forms
Add example. Fix: scope new is only special for class types.
1 parent 467f934 commit 54bd820

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

spec/expression.dd

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2358,9 +2358,44 @@ $(GNAME ArgumentList):
23582358
collected) heap.
23592359
)
23602360

2361-
$(P If a $(I NewExpression) is used as an initializer for
2361+
$(P The *Type* form constructs an instance of a type and default-initializes it.)
2362+
$(P The *Type(ArgumentList)* form allows passing either a single initializer
2363+
of the same type, or multiple arguments for more complex types.
2364+
For class types, *ArgumentList* is passed to the class constructor.
2365+
For a dynamic array, the argument sets the initial array length.
2366+
For multidimensional dynamic arrays, each argument corresponds to
2367+
an initial length.)
2368+
2369+
$(SPEC_RUNNABLE_EXAMPLE_RUN
2370+
---
2371+
int* i = new int;
2372+
assert(*i == 0);
2373+
i = new int(5);
2374+
assert(*i == 5);
2375+
2376+
Object o = new Object;
2377+
Exception e = new Exception("info");
2378+
2379+
auto a = new int[](2);
2380+
assert(a.length == 2);
2381+
2382+
int[][] m = new int[][](10, 5);
2383+
assert(m.length == 10);
2384+
assert(m[0].length == 5);
2385+
---
2386+
)
2387+
2388+
$(P The *Type[AssignExpression]* form allocates a dynamic array with
2389+
length equal to *AssignExpression*.
2390+
It is preferred to use the *Type(ArgumentList)* form when allocating
2391+
dynamic arrays instead, as it is more general.)
2392+
2393+
$(NOTE It is not possible to allocate a static array directly with
2394+
`new` (only by using a type alias).
2395+
2396+
$(P If a $(I NewExpression) is used with a class type as an initializer for
23622397
a function local variable with $(DDSUBLINK spec/attribute, scope, `scope`) storage class,
2363-
then the instance is allocated on the stack.
2398+
then the instance is $(DDSUBLINK spec/attribute, scope-class-var, allocated on the stack).
23642399
)
23652400

23662401
$(P `new` can also be used to allocate a

0 commit comments

Comments
 (0)