Luabind class deriving problem (memory 'leak&#

2019-07-27 11:16发布

Using luabind 0.81

Simple test to illustrate the problem:

1)

class 'A'
function A:__init()
   print('A init\n')
end
function A:__finalize()
   print('A finalize\n')
end

do
   local obj = A()
end
collectgarbage("collect")

Output:
A init
A finalize

2)

class 'A'
function A:__init()
   print('A init\n')
end
function A:__finalize()
   print('A finalize\n')
end

class 'B' (A)
function B:__init()
   A.__init(self)
   print('B init\n')
end
function B:__finalize()
   print('B finalize\n')
end

do
   local obj = B()
end
collectgarbage('collect')

Output:
A init
B init

Problem: Class with parent is not deleted on garbage collection.

How to solve this problem? Thank you.

1条回答
我想做一个坏孩纸
2楼-- · 2019-07-27 12:03

See Storing a lua class with parent in luabind::object. This is the same problem. The B instance is left in a "super" upvalue.

Setting the global super to nil before calling collectgarbage() should make the problem go away:

class 'A'
function A:__init()
   print('A init\n')
end
function A:__finalize()
   print('A finalize\n')
end

class 'B' (A)
function B:__init()
   A.__init(self)
   print('B init\n')
end
function B:__finalize()
   print('B finalize\n')
end

do
   local obj = B()
   super = nil
end
collectgarbage('collect')
查看更多
登录 后发表回答