请参阅此相关问题以获取一些背景信息。
注意:当我说“无效引用”时,我指的是没有指向数据的引用。
假设我们有以下包含循环引用的数据结构:
+-----------------------------------------------------+
| |
+-->+============+ +==========+ |
[ Reference ----->[ Blessed ] |
$parent -->+============+ [ Hash ] |
[ ] +==========+ |
[ children --->[ Array ] |
[ ] [ ] |
+==========+ [ 0: ---------+ |
[ ] | |
+==========+ | |
| |
+--------------------------------------------------+ |
| |
+-->+============+ +==========+ |
[ Reference ----->[ Blessed ] |
$child --->+============+ [ Hash ] |
[ ] |
[ parent: ----------------------+
[ ]
+==========+
我知道我可以使用Scalar::Util
'sweaken
函数来“弱化”引用。. . 但是,如果我削弱了来自的引用parent->child
并削弱了来自的引用child->parent
,然后其中一个$child
或$parent
超出范围,但不是另一个,会发生什么?
示例: $parent
超出范围,因此引用消失了。
+-----------------------------------------------------+
| |
+-->+============+ +==========+ |
[ Reference ----->[ Blessed ] |
+============+ [ Hash ] |
[ ] +==========+ |
[ children --->[ Array ] |
[ ] [ ] |
+==========+ [ 0: ---------+ |
[ ] | |
+==========+ | |
| |
would this break the link? ------------> X X
| |
+--------------------------------------------------+ |
| |
+-->+============+ +==========+ |
[ Reference ----->[ Blessed ] |
$child --->+============+ [ Hash ] |
[ ] |
[ parent: ----------------------+ <--- would this parent object pointer now be invalid?
[ ]
+==========+
如果我这样做了,然后“父对象”超出范围,是否会因为 Perl 对该对象的内部引用计数变为 0 而从内存中删除父对象?我问这个,因为如果$child
仍然存在并且需要使用来自父对象的一些数据,这会导致问题,因为子对象现在将持有指向父对象的无效指针。