【问题标题】:Ada Generics: Stack vs Heap ClarificationAda 泛型:堆栈与堆澄清
【发布时间】:2017-02-05 07:38:11
【问题描述】:

所以我有一个作业说:

请使用包/类的通用实例化。每个 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;

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;

同样,发布的代码与分配无关,但我的问题是,在发布的代码中,每次我使用“新”这个词时,是在堆栈还是堆中分配空间。因为我的指示说不要使用这个词,但是它说要使用我认为需要它的通用实例化。我将不胜感激!

【问题讨论】:

  • 不知道你是不是和this question上的课一样?如果这些问题中的任何一个要作为重复关闭,我认为应该是另一个!
  • 我认为你是对的。据我所知,未来作业的所有方向都写得这么差。还好我找到了这个网站。 @西蒙·赖特

标签: generics heap-memory instantiation ada stack-memory


【解决方案1】:

说明书上说

您特别不能使用“new”、“malloc”或任何其他运算符,它们会在运行时以任何语言在堆中分配空间。

这显然意味着你不能进行堆分配(为什么他们不能首先说我不知道​​;可能更清楚)。 “操作员”后面的逗号具有误导性。

实例化泛型通常发生在编译时;但即使你这样做了

Ada.Integer_IO.Get (N);
declare
   package Inst is new Some_Generic (N);
begin
   ...
end;

实例化本身不涉及堆分配。

您可以编写泛型,以便上面的实例化分配堆栈:

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;

甚至堆:

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;

但这是因为您在泛型中编写的代码,而不是需要您使用单词 new 来实例化它的语法。

【讨论】:

  • 那么在堆栈中实例化一个泛型分配?好的,那么在堆中分配某些东西的示例是什么样的?
  • 我添加了几个泛型示例,它们在实例化时会涉及分配,希望对您有所帮助
  • 啊,如果我错了,请纠正我:1)我在问题中发布的方式确实在堆栈中分配。 2)为了在堆中分配,我需要在泛型中使用“new”这个词,就像你对数组所做的那样。顺便说一句,感谢您的宝贵时间!
  • 你的genericArray 没有声明它自己的任何数据对象,只是一个类型,所以package createShotArrayType 可能没有分配任何东西。对象vaccine 将在堆栈上创建。 (我不太确定“system stack”的原始问题是什么意思)。
  • 我也不是,我只知道这家伙讨厌堆上的数据,只要分配到那里,他就会扣掉 10+ 分,所以我只是偏执,谢谢你时间!
猜你喜欢
  • 1970-01-01
  • 2015-07-19
  • 2014-06-23
  • 1970-01-01
  • 2015-04-04
  • 2011-05-04
  • 2012-01-18
  • 2012-10-12
  • 2011-10-06
相关资源
最近更新 更多