Luabind class deriving problem (memory 'leak&#

2019-07-27 11:40发布

问题:

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:

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')