【发布时间】:2017-10-19 23:29:13
【问题描述】:
我想通过以下方式创建一个用于创建和初始化受控类型(有点像工厂)的函数:
function Create return Controlled_Type
is
Foo : Controlled_Type;
begin
Put_Line ("Check 1")
return Foo;
end Create;
procedure Main
is
Bar : Controlled_Type := Create;
begin
Put_Line ("Check 2")
end Main;
output:
Initialize
Check 1
Adjust
Finalize
由于 finalize 将处理一些在受控类型中指向的对象,我最终会在 Bar 中出现悬空指针,并且不知何故这会立即使程序崩溃,所以我永远不会看到“检查 2”。
这可以通过使用新的 Controlled_Type 并在 Create 函数中返回一个指针来轻松解决。但是,我喜欢拥有受控类型而不是指向它的指针的想法,因为当 Bar 超出范围时将自动调用终结。如果 Bar 是一个指针,我必须手动处理它。
有什么方法可以正确地做到这一点而不会出现悬空指针?我应该在 Adjust 过程中施展魔法吗?
【问题讨论】:
标签: factory ada dangling-pointer finalization