Lua 中丢失引用

发布于 2024-08-16 02:55:21 字数 165 浏览 3 评论 0原文

对象出现问题,不再需要但仍然有引用。 结果:由于未收集对象,分配的内存大小不断增长。

遇到这样的问题该如何解决呢? 有没有办法找到只有一个引用的对象,或者生命周期超过某个值的对象?或者还有其他解决方案吗?

使用 Lua 5.1 和 C++ 与 luabind。

谢谢。

Having a problem with objects, not needed any more but still having references.
Result: size of allocated memory is constantly growing due to not collected objects.

How to solve this sort of problem?
Is there any way to find objects with only one reference, or objects with lifetime more than some value? Or any another solution?

Using Lua 5.1 and C++ with luabind.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

本宫微胖 2024-08-23 02:55:21

正如有人在这里提到的,您可以尝试使用弱表

如果您有这样的代码:

myListOfObjects = {}
...
table.insert(myListOfObject, anObject)

那么一旦 anObject 停止使用,它就永远不会被释放,因为 myListOfObjects 仍然引用它。

您可以尝试删除 myListOfObjects 中的引用(将引用设置为 nil),但更简单的解决方案是将 myListOfObjects 声明为弱表

myListOfObjects = {}
setmetatable(myListOfObjects, { __mode = 'v' }) --myListOfObjects is now weak

鉴于setmetatable 返回对其修改的表的引用,您可以使用这个更短的习惯用法,其作用与前两行相同:

myListOfObjects = setmetatable({}, {__mode = 'v' }) --creation of a weak table

As someone is mentioning here, you can try using weak tables.

If you have some code like this:

myListOfObjects = {}
...
table.insert(myListOfObject, anObject)

Then once anObject stops being used, it will never be deallocated since myListOfObjects still references it.

You could try removing the reference in myListOfObjects (setting the reference to nil) but a simpler solution is declaring myListOfObjects as a weak table:

myListOfObjects = {}
setmetatable(myListOfObjects, { __mode = 'v' }) --myListOfObjects is now weak

Given that setmetatable returns a reference to the table it modifies, you can use this shorter idiom, which does the same as previous two lines:

myListOfObjects = setmetatable({}, {__mode = 'v' }) --creation of a weak table
白鸥掠海 2024-08-23 02:55:21

我不确定是否将其与 C++ 集成,但听起来垃圾收集器没有机会运行。

在你的 lua 中,你可以尝试显式调用它,看看是否有帮助。核心api中有一个函数collectgarbage(opt [, arg])

I'm not certain about integrating it with C++ but it sounds like the garbage collector isn't being given an opportunity to run.

In your lua you could try explicitly invoking it and see if that helps. There is a function in the core apis collectgarbage(opt [, arg]).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文