7.6 Assignment and Finalization
This Reference Manual output has not been verified, and may contain omissions or errors. Report any problems on the tracking issue
[ Three kinds of actions are fundamental to the manipulation of objects: initialization, finalization, and assignment. Every object is initialized, either explicitly or by default, after being created (for example, by an object_declaration
or allocator
). Every object is finalized before being destroyed (for example, by leaving a subprogram_body
containing an object_declaration
, or by a call to an instance of Unchecked_Deallocation). An assignment operation is used as part of assignment_statement
s, explicit initialization, parameter passing, and other operations.
Default definitions for these three fundamental operations are provided by the language, but a controlled type gives the user additional control over parts of these operations. In particular, the user can define, for a controlled type, an Initialize procedure which is invoked immediately after the normal default initialization of a controlled object, a Finalize procedure which is invoked immediately before finalization of any of the components of a controlled object, and an Adjust procedure which is invoked as the last step of an assignment to a (nonlimited) controlled object.]
aggregate
or function call (in which case neither Adjust nor Initialize is applied), or the assignment copies and adjusts the initial value. Otherwise, Initialize is applied to it (except in the case of an aggregate
as a whole). An assignment_statement
finalizes the target before copying in and adjusting the new value. Whenever an object goes away, it is finalized. Calls on Initialize and Adjust happen bottom-up; that is, components first, followed by the containing object. Calls on Finalize happen top-down; that is, first the containing object, and then its components. These ordering rules ensure that any components will be in a well-defined state when Initialize, Adjust, or Finalize is applied to the containing object. Static Semantics
4The following language-defined library package exists:
{8652/0020} package Ada.Finalization
with Pure, Nonblocking => False is
6/5type Controlled is abstract tagged private
with Preelaborable_Initialization ;
7/2procedure Initialize (Object : in out Controlled) is null;
procedure Adjust (Object : in out Controlled) is null;
procedure Finalize (Object : in out Controlled) is null;
8/5type Limited_Controlled is abstract tagged limited private
with Preelaborable_Initialization ;
9/2procedure Initialize (Object : in out Limited_Controlled) is null;
procedure Finalize (Object : in out Limited_Controlled) is null;
private
... -- not specified by the language
end Ada.Finalization;
A controlled type is a descendant of Controlled or Limited_Controlled. The predefined "=" operator of type Controlled always returns True, [since this operator is incorporated into the implementation of the predefined equality operator of types derived from Controlled, as explained in 4.5.2.] The type Limited_Controlled is like Controlled, except that it is limited and it lacks the primitive subprogram Adjust.
A type is said to need finalization if:
- it is a controlled type, a task type or a protected type; or
- it has a component whose type needs finalization; or
- it is a class-wide type; or
- it is a partial view whose full view needs finalization; or
- it is one of a number of language-defined types that are explicitly defined to need finalization.
Dynamic Semantics
11/2During the elaboration or evaluation of a construct that causes an object to be initialized by default, for every controlled subcomponent of the object that is not assigned an initial value (as defined in 3.3.1), Initialize is called on that subcomponent. Similarly, if the object that is initialized by default as a whole is controlled, Initialize is called on the object.
{8652/0021} For an extension_aggregate
whose ancestor_part
is a subtype_mark
denoting a controlled subtype, the Initialize procedure of the ancestor type is called, unless that Initialize procedure is abstract.
type T1 is new Controlled with
record
... -- some components might have defaults
end record;
12.ctype T2 is new Controlled with
record
X : T1; -- no default
Y : T1 := ...; -- default
end record;
12.dA : T2;
B : T2 := ...;
ancestor_part
of an extension_aggregate
, <> in aggregates, and the return object of an extended_return_statement
are handled similarly. Initialize and other initialization operations are done in an arbitrary order, except as follows. Initialize is applied to an object after initialization of its subcomponents, if any [(including both implicit initialization and Initialize calls)]. If an object has a component with an access discriminant constrained by a per-object expression, Initialize is applied to this component after any components that do not have such discriminants. For an object with several components with such a discriminant, Initialize is applied to them in order of their component_declaration
s. For an allocator
, any task activations follow all calls on Initialize.
When a target object with any controlled parts is assigned a value, [either when created or in a subsequent assignment_statement
,] the assignment operation proceeds as follows:
- The value of the target becomes the assigned value.
- The value of the target is adjusted.
To adjust the value of a composite object, the values of the components of the object are first adjusted in an arbitrary order, and then, if the object is nonlimited controlled, Adjust is called. Adjusting the value of an elementary object has no effect[, nor does adjusting the value of a composite object with no controlled parts.]
For an assignment_statement
, [ after the name
and expression
have been evaluated, and any conversion (including constraint checking) has been done,] an anonymous object is created, and the value is assigned into it; [that is, the assignment operation is applied]. [(Assignment includes value adjustment.)] The target of the assignment_statement
is then finalized. The value of the anonymous object is then assigned into the target of the assignment_statement
. Finally, the anonymous object is finalized. [As explained below, the implementation may eliminate the intermediate anonymous object, so this description subsumes the one given in 5.2, “Assignment Statements”.]
procedure Assign(Target : in out Controlled; Source : in out Controlled);
procedure ":="(Target : in out Controlled; Source : in out Controlled);
type Mutable(D : Integer := 0) is
record
X : Array_Of_Controlled_Things(1..D);
case D is
when 17 => Y : Controlled_Thing;
when others => null;
end D;
end record;
When a function call or aggregate
is used to initialize an object, the result of the function call or aggregate
is an anonymous object, which is assigned into the newly-created object. For such an assignment, the anonymous object may be built in place, in which case the assignment does not involve any copying. Under certain circumstances, the anonymous object is required to be built in place. In particular:
- If the full type of any part of the object is immutably limited, the anonymous object is built in place.
- In the case of an
aggregate
, if the full type of any part of the newly-created object is controlled, the anonymous object is built in place.
package P is
type Dyn_String is private;
Null_String : constant Dyn_String;
...
private
type Dyn_String is new Ada.Finalization.Controlled with ...
procedure Finalize(X : in out Dyn_String);
procedure Adjust(X : in out Dyn_String);
Null_String : constant Dyn_String :=
(Ada.Finalization.Controlled with ...);
...
end P;
aggregate
with a controlled part used in the return expression of a simple_return_statement
has to be built in place in the anonymous return object, as this is similar to an object declaration. (This is a change from Ada 95, but it is not an inconsistency as it only serves to restrict implementation choices.) But this only covers the aggregate
; a separate anonymous return object can still be used unless it too is required to be built in place.aggregate
that has a controlled part but is not itself controlled and that is used to initialize an object also has to be built in place. This is also a change from Ada 95, but it is not an inconsistency as it only serves to restrict implementation choices. This avoids problems if a type like Dyn_String (in the example above) is used as a component in a type used as a deferred constant in package P. - In other cases, it is unspecified whether the anonymous object is built in place.
Notwithstanding what this document says elsewhere, if an object is built in place:
- Upon successful completion of the return statement or
aggregate
, the anonymous object mutates into the newly-created object; that is, the anonymous object ceases to exist, and the newly-created object appears in its place. 18.7/3 - Finalization is not performed on the anonymous object.
- Adjustment is not performed on the newly-created object.
- All access values that designate parts of the anonymous object now designate the corresponding parts of the newly-created object.
- All renamings of parts of the anonymous object now denote views of the corresponding parts of the newly-created object.
- Coextensions of the anonymous object become coextensions of the newly-created object.
extension_aggregate
, then the tag of the anonymous object (the function result) will be different from the tag of the newly-created object (the ancestor part of the extension_aggregate
). In implementation terms, this involves modifying the tag field. If the current task is aborted during this modification, the object might become abnormal. Likewise, if some other task accesses the tag field during this modification, it constitutes improper use of shared variables, and is erroneous. Implementation Permissions
19/3An implementation is allowed to relax the above rules for assignment_statement
s in the following ways:
assignment_statement
s are not allowed for limited types. This is important so that the programmer can count on stricter semantics for limited controlled types. - If an object is assigned the value of that same object, the implementation may omit the entire assignment .
- For assignment of a noncontrolled type, the implementation may finalize and assign each component of the variable separately (rather than finalizing the entire variable and assigning the entire new value) unless a discriminant of the variable is changed by the assignment.
- The implementation may avoid creating an anonymous object if the value being assigned is the result of evaluating a
name
denoting an object (the source object) whose storage cannot overlap with the target. If the source object can overlap with the target object, then the implementation can avoid the need for an intermediary anonymous object by exercising one of the above permissions and perform the assignment one component at a time (for an overlapping array assignment), or not at all (for an assignment where the target and the source of the assignment are the same object).
Furthermore, an implementation is permitted to omit implicit Initialize, Adjust, and Finalize calls and associated assignment operations on an object of a nonlimited controlled type provided that:
- any omitted Initialize call is not a call on a user-defined Initialize procedure, and
- any usage of the value of the object after the implicit Initialize or Adjust call and before any subsequent Finalize call on the object does not change the external effect of the program, and
- after the omission of such calls and operations, any execution of the program that executes an Initialize or Adjust call on an object or initializes an object by an
aggregate
will also later execute a Finalize call on the object and will always do so prior to assigning a new value to the object, and 27/2 - the assignment operations associated with omitted Adjust calls are also omitted.
This permission applies to Adjust and Finalize calls even if the implicit calls have additional external effects.
Extensions to Ada 83
Extensions to Ada 95
Wording Changes from Ada 95
aggregate
used for the initialization of an object or subaggregate, or passed as a parameter.aggregate
s to be consistent with the requirements for limited types.Extensions to Ada 2005
Wording Changes from Ada 2005
7.6.1 Completion and Finalization
1[This subclause defines completion and leaving of the execution of constructs and entities. A master is the execution of a construct that includes finalization of local objects after it is complete (and after waiting for any local tasks — see 9.3), but before leaving. Other constructs and entities are left immediately upon completion. ]
Dynamic Semantics
2/2The execution of a construct or entity is complete when the end of that execution has been reached, or when a transfer of control (see 5.1) causes it to be abandoned. Completion due to reaching the end of execution, or due to the transfer of control of an exit_statement
, return statement, goto_statement
, or requeue_statement
or of the selection of a terminate_alternative
is normal completion. Completion is abnormal otherwise [— when control is transferred out of a construct due to abort or the raising of an exception].
After execution of a construct or entity is complete, it is left, meaning that execution continues with the next action, as defined for the execution that is taking place. Leaving an execution happens immediately after its completion, except in the case of the execution of a master construct : a body other than a package_body
; a statement
; or an expression
, function_call
, or range
that is not part of an enclosing expression
, function_call
, range
, or simple_statement
other than a simple_return_statement
. The term master by itself refers to the execution of a master construct. A master is finalized after it is complete, and before it is left.
Expression
s and statement
s are masters so that objects created by subprogram calls (in aggregate
s, allocator
s for anonymous access-to-object types, and so on) are finalized and have their tasks awaited before the expression
s or statement
s are left. Note that expression
s like the condition
of an if_statement
are masters, because they are not enclosed by a simple_statement
. Similarly, a function_call
which is renamed is a master, as it is not in a simple_statement
.function_call
s in the contexts that do not cause masters to occur so that expression
s contained in a function_call
(that is not part of an expression
or simple_statement
) do not individually become masters. We certainly do not want the parameter expression
s of a function_call
to be separate masters, as they would then be finalized before the function is called. function_call
is a master does not change the accessibility of the return object denoted by the function_call
; that depends on the use of the function_call
. The function_call
is the master of any short-lived entities (such as aggregate
s used as parameters of types with task or controlled parts). allocator
s (if the ultimate ancestor access type is declared in one of those places) and subcomponents of all of these things. If an object was already finalized by Unchecked_Deallocation, then it is not finalized again when the master is left.For the finalization of an object:
- If the full type of the object is an elementary type, finalization has no effect;
- If the full type of the object is a tagged type, and the tag of the object identifies a controlled type, the Finalize procedure of that controlled type is called;
- If the full type of the object is a protected type, or if the full type of the object is a tagged type and the tag of the object identifies a protected type, the actions defined in 9.4 are performed;
- If the full type of the object is a composite type, then after performing the above actions, if any, every component of the object is finalized in an arbitrary order, except as follows: if the object has a component with an access discriminant constrained by a per-object expression, this component is finalized before any components that do not have such discriminants; for an object with several components with such a discriminant, they are finalized in the reverse of the order of their
component_declaration
s;
- If the object has coextensions (see 3.10.2), each coextension is finalized after the object whose access discriminant designates it.
aggregate
or function call that is used (in its entirety) to directly initialize a part of an object, the coextensions of the result of evaluating the aggregate
or function call are transfered to become coextensions of the object being initialized and are not finalized until the object being initialized is ultimately finalized, even if an anonymous object is created as part of the operation. Immediately before an instance of Unchecked_Deallocation reclaims the storage of an object, the object is finalized. [If an instance of Unchecked_Deallocation is never applied to an object created by an allocator
, the object will still exist when the corresponding master completes, and it will be finalized then.]
The finalization of a master performs finalization of objects created by declarations in the master in the reverse order of their creation. After the finalization of a master is complete, the objects finalized as part of its finalization cease to exist, as do any types and subtypes defined and created within the master.
Each nonderived access type T has an associated collection, which is the set of objects created by allocator
s of T, or of types derived from T. Unchecked_Deallocation removes an object from its collection. Finalization of a collection consists of finalization of each object in the collection, in an arbitrary order. The collection of an access type is an object implicitly declared at the following place:
allocator
type, not according to the storage pool in which they are allocated. Pool finalization might reclaim storage (see 13.11, “Storage Management”), but has nothing (directly) to do with finalization of the pool elements.- For a named access type, the first freezing point (see 13.14) of the type.
- For the type of an access parameter, the call that contains the
allocator
. 12.4/3 - For the type of an access result, within the master of the call (see 3.10.2).
- For any other anonymous access type, the first freezing point of the innermost enclosing declaration.
The target of an assignment_statement
is finalized before copying in the new value, as explained in 7.6.
{8652/0021} The master of an object is the master enclosing its creation whose accessibility level (see 3.10.2) is equal to that of the object, except in the case of an anonymous object representing the result of an aggregate
or function call. If such an anonymous object is part of the result of evaluating the actual parameter expression for an explicitly aliased parameter of a function call, the master of the object is the innermost master enclosing the evaluation of the aggregate
or function call, excluding the aggregate
or function call itself. Otherwise, the master of such an anonymous object is the innermost master enclosing the evaluation of the aggregate
or function call, which may be the aggregate
or function call itself.
This paragraph was deleted.
allocator
s, and so on, and applies them to determine where objects created in them are finalized. For instance, the master of a rename of a subprogram is that of the renamed subprogram.aggregate
or function call that is used to directly initialize a part of an object based on the object being initialized. This is important to ensure that any access discriminants denote objects that live at least as long as the object being initialized. However, if the result of the aggregate
or function call is not built directly in the target object, but instead is built in an anonymous object that is then assigned to the target, the anonymous object needs to be finalized after the assignment rather than persisting until the target object is finalized (but not its coextensions). (Note than an implementation is never required to create such an anonymous object, and in some cases is required to not have such a separate object, but rather to build the result directly in the target.)allocator
, for instance). In that case, the accessibility check on explicitly aliased parameters will necessarily fail if any such anonymous objects exist. This is necessary to avoid requiring the objects to live as long as the access type or having the implementation complexity of an implicit coextension. {8652/0023} In the case of an expression
that is a master, finalization of any (anonymous) objects occurs after completing evaluation of the expression
and all use of the objects, prior to starting the execution of any subsequent construct.
Bounded (Run-Time) Errors
15/1{8652/0023} It is a bounded error for a call on Finalize or Adjust that occurs as part of object finalization or assignment to propagate an exception. The possible consequences depend on what action invoked the Finalize or Adjust operation:
- For a Finalize invoked as part of an
assignment_statement
, Program_Error is raised at that point. 17/5 - {8652/0024} For an Adjust invoked as part of assignment operations other than those invoked as part of an
assignment_statement
, some of the adjustments due to be performed can be performed, and then Program_Error is raised. During its propagation, finalization may be applied to objects whose Adjust failed. For an Adjust invoked as part of anassignment_statement
, any other adjustments due to be performed are performed, and then Program_Error is raised.
assignment_statement
, it is important that all adjustments be performed, even if one fails, because all controlled subcomponents are going to be finalized. Other kinds of assignment are more like initialization than assignment_statement
s, so we include them as well in the permission. - For a Finalize invoked as part of a call on an instance of Unchecked_Deallocation, any other finalizations due to be performed are performed, and then Program_Error is raised.
allocator
's master is finalized). - This paragraph was deleted.{8652/0023}
- {8652/0023} For a Finalize invoked due to reaching the end of the execution of a master, any other finalizations associated with the master are performed, and Program_Error is raised immediately after leaving the master.
expression
. All contexts that create objects that need finalization are defined to be masters. - For a Finalize invoked by the transfer of control of an
exit_statement
, return statement,goto_statement
, orrequeue_statement
, Program_Error is raised no earlier than after the finalization of the master being finalized when the exception occurred, and no later than the point where normal execution would have continued. Any other finalizations due to be performed up to that point are performed before raising Program_Error.
block_statement
due to a goto_statement
, the Program_Error would be raised at the point of the target statement denoted by the label, or else in some more dynamically nested place, but not so nested as to allow an exception_handler
that has visibility upon the finalized object to handle it. For example, procedure Main is
begin
<<The_Label>>
Outer_Block_Statement : declare
X : Some_Controlled_Type;
begin
Inner_Block_Statement : declare
Y : Some_Controlled_Type;
Z : Some_Controlled_Type;
begin
goto The_Label;
exception
when Program_Error => ... -- Handler number 1.
end;
exception
when Program_Error => ... -- Handler number 2.
end;
exception
when Program_Error => ... -- Handler number 3.
end Main;
goto_statement
will first cause Finalize(Z ) to be called. Suppose that Finalize(Z ) propagates an exception. Program_Error will be raised after leaving Inner_Block_Statement, but before leaving Main. Thus, handler number 1 cannot handle this Program_Error; it will be handled either by handler number 2 or handler number 3. If it is handled by handler number 2, then Finalize(Y ) will be done before executing the handler. If it is handled by handler number 3, then Finalize(Y ) and Finalize(X) will both be done before executing the handler. - For a Finalize invoked by a transfer of control that is due to raising an exception, any other finalizations due to be performed for the same master are performed; Program_Error is raised immediately after leaving the master.
goto_statement
were replaced by a raise_statement
, then the Program_Error would be handled by handler number 2, and Finalize(Y ) would be done before executing the handler. exception_handler
s useless. For example, suppose the only exception_handler
is one for others in the main subprogram. If some deeply nested call raises an exception, causing some Finalize operation to be called, which then raises an exception, then normal execution “would have continued” at the beginning of the exception_handler
. Raising Program_Error at that point would cause that handler's code to be skipped. One would need two nested exception_handler
s to be sure of catching such cases!exception_handler
for a given master should not be allowed to handle exceptions raised during finalization of that master. - For a Finalize invoked by a transfer of control due to an abort or selection of a terminate alternative, the exception is ignored; any other finalizations due to be performed are performed.
Implementation Permissions
21.1/3If the execution of an allocator
propagates an exception, any parts of the allocated object that were successfully initialized may be finalized as part of the finalization of the innermost master enclosing the allocator
.
The implementation may finalize objects created by allocator
s for an access type whose storage pool supports subpools (see 13.11.4) as if the objects were created (in an arbitrary order) at the point where the storage pool was elaborated instead of at the first freezing point of the access type.
allocator
s of library-level access types, except those already finalized). This occurs after waiting for library-level tasks to terminate. assignment_statement
if the type is nonlimited, and an abort is permitted to disrupt an assignment_statement
between finalizing the left-hand side and assigning the new value to it (an abort is not permitted to disrupt an assignment operation between copying in the new value and adjusting it). aggregate
(both the anonymous object created for an aggregate, or an object initialized by an aggregate
that is built-in-place); Initialize is not applied to the aggregate
as a whole, nor is the value of the aggregate
or object adjusted.- the
assignment_statement
(see 5.2); 25.f - explicit initialization of a stand-alone object (see 3.3.1) or of a pool element (see 4.8);
- default initialization of a component of a stand-alone object or pool element (in this case, the value of each component is assigned, and therefore adjusted, but the value of the object as a whole is not adjusted);
- function return, when the result is not built-in-place (adjustment of the result happens before finalization of the function);
- predefined operators (although the only one that matters is concatenation; see 4.5.3);
- generic formal objects of mode in (see 12.4); these are defined in terms of constant declarations; and
aggregate
s (see 4.3), when the result is not built-in-place (in this case, the value of each component, and the ancestor part, for anextension_aggregate
, is assigned, and therefore adjusted, but the value of theaggregate
as a whole is not adjusted; neither is Initialize called);
- By-copy parameter passing uses the assignment operation (see 6.4.1), but controlled objects are always passed by reference, so the assignment operation never does anything interesting in this case. If we were to allow by-copy parameter passing for controlled objects, we would need to make sure that the actual is finalized before doing the copy back for [in] out parameters. The finalization of the parameter itself needs to happen after the copy back (if any), similar to the finalization of an anonymous function return object or
aggregate
object. 25.n - For loops use the assignment operation (see 5.5), but since the type of the loop parameter is never controlled, nothing interesting happens there, either.
- Objects initialized by function results and
aggregate
s that are built-in-place. In this case, the assignment operation is never executed, and no adjustment takes place. While built-in-place is always allowed, it is required for some types — see 7.5 and 7.6 — and that's important since limited types have no Adjust to call.
Wording Changes from Ada 83
Inconsistencies With Ada 95
Wording Changes from Ada 95
assignment_statement
s.expression
s and statement
s, in order to cleanly define what happens for tasks and controlled objects created as part of a subprogram call. Having done that, all of the special wording to cover those cases is eliminated (at least until the Ada comments start rolling in).Inconsistencies With Ada 2005
Wording Changes from Ada 2005
allocator
s. This could be an inconsistency, but the previous behavior is still allowed and there is no requirement that implementations take advantage of the permission.