Lua/Luabind:由对象构建的对象仍然保留分配。

我有一个简单的Lua脚本

function TestFunction(Id)
    local Factory = TestParent();
    local ChildDirect = TestChild("DirectCall");
    local ChildFactory1 = Factory:CreateChild("Factory1");
    local ChildFactory2 = Factory:CreateChild("Factory2");

    result = Ret()
    return result
end

它使用两个通过luabind暴露出来的C++对象

void TestParent::RegisterToLua(lua_State* lua)
{
  // Export our class with LuaBind
  luabind::module(lua)
    [
        luabind::class_<TestParent>("TestParent")
            .def(luabind::constructor<>())
            .def("CreateChild", &TestParent::CreateChild)
    ];
}

void TestChild::RegisterToLua(lua_State* lua)
{
  // Export our class with LuaBind
  luabind::module(lua)
    [
        luabind::class_<TestChild>("TestChild")
            .def(luabind::constructor<std::string>())
            .def("GetValue", &TestChild::GetValue)
    ];
}

我调用函数

luabind::object obj = luabind::call_function< luabind::object >(LuaState, "TestFunction", IdParam);

if ( obj.is_valid() )
{
        ....
}

lua_gc(LuaState, LUA_GCCOLLECT, 0);

lua_gc调用期间,只有FactoryChildDirect对象被销毁。 ChildFactory1和ChildFactory2保持分配状态。在luabind::call_function之后,lua栈保持平衡(具有相同的值-5-某些表)。

问题是什么?工厂创建的对象仍然被引用?由谁引用?

CreateChild的主体是

TestChild * TestParent :: CreateChild(std :: string strname)
{
    返回新的TestChild(strname);
}

新构造对象的所有权应由lua对象接管,并在ChildFactory1或ChildFactory2nil或超出范围时销毁。

点赞
用户847349
用户847349

你应该从你的工厂函数返回一个智能指针(即 boost::shared_ptr)。

见:LuaBind 文档 # 智能指针

还有一个讨论在 LuaBridge 文档

2014-01-16 18:37:24
用户572586
用户572586

adopt: 用于跨语言边界传递所有权。

module(L)
[
    def("create", &create, adopt(result))//使用 adopt将所有权从 C++ 传递到 Lua
];
2014-01-16 21:30:39