简体   繁体   English

lua - 类析构函数的延迟调用

[英]lua - late call of class destructor

I am working on a c++ program which essentially just executes a lua script. 我正在研究一个基本上只执行lua脚本的c ++程序。 In that lua script however classes are constructed, which have been exported from my c++ program to the lua script. 在那个lua脚本中,然而构造了类,这些类已经从我的c ++程序导出到lua脚本。

My main() c++ function just calls after some preparations... 我的main()c ++函数只是在做了一些准备之后调用了...

    luabind::call_function<void>(m_L, "main");

Now my lua script looks like this 现在我的lua脚本看起来像这样

local function test()
local c = C()
end

function main()
    for i=1,2 do
        log(i)
        test()
    end
end

I have included a std::cout << "destructor" << std::endl; 我已经包含了一个std :: cout <<“析构函数”<< std :: endl; in C's destructor so I know when it is called. 在C的析构函数中所以我知道它什么时候被调用。 I would expect that lua's garbage collection calls the destructor of c everytime execution of test() ends, because that is when it falls out of scope. 我希望lua的垃圾收集在每次执行test()时都会调用c的析构函数,因为那时它就超出了范围。 Instead I see the following output: 相反,我看到以下输出:

1
2
destructor
destructor

rather than 而不是

1
destructor
2
destructor

Does anyone have an idea why this is? 有谁知道为什么会这样? Am I missing something here? 我在这里错过了什么吗?

I would expect that lua's garbage collection calls the destructor of c everytime execution of test() ends, because that is when it falls out of scope. 我希望lua的垃圾收集在每次执行test()时都会调用c的析构函数,因为那时它就超出了范围。

This is not the case. 不是这种情况。 Lua's garbage collection does not run at the end of every scope. Lua的垃圾收集不会在每个范围的末尾运行。 It is typical of garbage collected languages that you can't depend on when exactly the destructors are run, and in some languages an object may never be destroyed at all. 垃圾收集语言的典型特征是在运行析构函数时无法依赖,在某些语言中,对象可能永远不会被销毁。

There is not any way to make Lua automatically destroy objects deterministically like C++ does. 没有任何方法可以让Lua像C ++那样确定性地自动销毁对象。

If you have to depend on this then you may be able to get by with Lua's collectgarbage function, however it would probably be better to simply change your expectations and redesign accordingly. 如果你必须依赖于这个,那么你可以使用Lua的collectgarbage功能,但是简单地改变你的期望并相应地重新设计可能会更好。

Here's the Lua documentation on how their garbage collection works. 这是关于他们的垃圾收集如何工作的Lua文档。


An example of using collectgarbage: 使用collectgarbage的一个例子:

local function test()
    local c = C()
end

function main()
    for i=1,2 do
        log(i)
        test()
        collectgarbage "collect"
    end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM