Lua 中丢失引用
对象出现问题,不再需要但仍然有引用。 结果:由于未收集对象,分配的内存大小不断增长。
遇到这样的问题该如何解决呢? 有没有办法找到只有一个引用的对象,或者生命周期超过某个值的对象?或者还有其他解决方案吗?
使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如有人在这里提到的,您可以尝试使用弱表。
如果您有这样的代码:
那么一旦
anObject
停止使用,它就永远不会被释放,因为myListOfObjects
仍然引用它。您可以尝试删除
myListOfObjects
中的引用(将引用设置为 nil),但更简单的解决方案是将myListOfObjects
声明为弱表:鉴于
setmetatable
返回对其修改的表的引用,您可以使用这个更短的习惯用法,其作用与前两行相同:As someone is mentioning here, you can try using weak tables.
If you have some code like this:
Then once
anObject
stops being used, it will never be deallocated sincemyListOfObjects
still references it.You could try removing the reference in
myListOfObjects
(setting the reference to nil) but a simpler solution is declaringmyListOfObjects
as a weak table: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:我不确定是否将其与 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])
.