我在使用Lua的C API编写应用程序,我试图确定使用它的方式是否会留下一些悬挂指针(指向指针)。C(++)和Lua清理内存
说我有树状结构(类实际上)在C++
- 假设tree
已经创建并包含数据,我在Lua使用它像这样:
local root = tree:getRoot()
root:DoSomeLeafStuff()
现在我的C的执行getRoot()
Lua看起来像这样:
int LuaStuff::TreeGetRoot(lua_State* L)
{
Tree* tree = *(Tree**)luaL_checkudata(L, 1, "MyStuff.Tree");
if (tree != NULL && tree->getRoot() != NULL)
{
int size = sizeof(Leaf**);
*((Leaf**)lua_newuserdata(L, size)) = tree->getRoot(); // allocate a pointer to a pointer
lua_setmetatable(L, "MyStuff.Leaf");
}
else
{
lua_pushnil(L);
}
return 1;
}
经过一些故障排除后,我能够在您期望的时候让我的Tree和Leaf对象释放。但到目前为止,我还没有找到一种令人信服的方式(至少对我来说)指针指针正在清理。
我的问题是:我可以安全地假设由Lua的lua_newuserdata()分配的内存由Lua的垃圾回收自动清理?
http://lua-users.org/wiki/GarbageCollectionTutorial – hjpotter92 2013-04-10 11:41:10