Num*_*rry 0 generics ada instantiation heap-memory stack-memory
所以我有一个作业说:
请使用包/类的通用实例化。必须在通用包/模板内的系统堆栈中为每个 BMR(矩阵)分配空间,可能是在通用实例化期间!您特别不能使用“new”、“malloc”或任何其他运算符,这些运算符在运行时以任何语言在堆中分配空间。用荧光笔清楚地标记这部分代码!您必须阅读所有事务并打印所有结果在通用包/模板中。I/O 例程必须作为通用参数传递
和不相关的代码:
generic
type subscript is (<>); --range variable to be instantiated
type myType is private; --type variable to be intantiated
package genericArray is
type userDefinedArray is array(subscript range <>) of myType;
end genericArray;
Run Code Online (Sandbox Code Playgroud)
with ada.text_io; use ada.text_io;
with genericArray;
procedure useGenericArray is
type month_name is (jan, feb, mar, apr, may, jun,
jul, aug, sep, oct, nov, dec);
type date is
record
day: integer range 1..31; month: month_name; year: integer;
end record;
type family is (mother, father, child1, child2, child3, child4);
package month_name_io is new ada.text_io.enumeration_io(month_name);
use month_name_io;
package IIO is new ada.text_io.integer_io(integer);
use IIO;
package createShotArrayType is new genericArray(family, date);
use createShotArrayType;
vaccine: userDefinedArray(family);
begin
vaccine(child2).month := jan;
vaccine(child2).day := 22;
vaccine(child2).year := 1986;
put("child2: ");
put(vaccine(child2).month);
put(vaccine(child2).day);
put(vaccine(child2).year); new_line;
end useGenericArray;
Run Code Online (Sandbox Code Playgroud)
同样,发布的代码与赋值无关,但我的问题是,在发布的代码中,每次我使用“new”这个词时,是在堆栈还是堆中分配空间。因为我的指示说不要使用这个词,但是它说要使用我认为需要它的通用实例化。我将不胜感激澄清!
说明说
您特别不能使用“new”、“malloc”或任何其他运算符,这些运算符在运行时以任何语言在堆中分配空间。
这显然意味着你不能做堆分配(为什么他们不能先说我不知道;可能更清楚)。“运算符”后面的逗号具有误导性。
实例化泛型通常发生在编译时;但即使你做了
Ada.Integer_IO.Get (N);
declare
package Inst is new Some_Generic (N);
begin
...
end;
Run Code Online (Sandbox Code Playgroud)
实例化本身不涉及堆分配。
您可以编写泛型,以便上面的实例化分配堆栈:
generic
J : Positive;
package Some_Generic is
type Arr is array (1 .. J) of Integer;
A : Arr; -- in a declare block, this ends up on the stack
end Some_Generic;
Run Code Online (Sandbox Code Playgroud)
甚至堆:
generic
J : Positive;
package Some_Generic is
type Arr is array (1 .. J) of Integer;
type Arr_P is access Arr;
P : Arr_P := new Arr; -- always on the heap
end Some_Generic;
Run Code Online (Sandbox Code Playgroud)
但那是因为您在泛型中编写的代码,而不是要求您使用该词new来实例化它的语法。