C++ 永远不会调用Lua\uu gc元方法
我有一个Vector类,它被包装成在Lua中工作。类的C++部分是:C++ 永远不会调用Lua\uu gc元方法,c++,lua,C++,Lua,我有一个Vector类,它被包装成在Lua中工作。类的C++部分是: template<typename T> CVector<T>::CVector(int len) { m_vector=new vector<T>(len); for(int i=0;i<len;i++) m_vector->at(i)=T(); } template<typename T> CVector<T>::~CVector(vo
template<typename T> CVector<T>::CVector(int len)
{
m_vector=new vector<T>(len);
for(int i=0;i<len;i++) m_vector->at(i)=T();
}
template<typename T> CVector<T>::~CVector(void)
{
if(m_vector){
m_vector->clear();
delete m_vector;
}
m_vector=0;
}
我的理解是,当
local v
超出范围时,它应该被垃圾收集。我显式地调用了collectgarbage
,但从未调用metamethod\uuu gc
,并且对于大向量,内存使用会增加,除非我使用v:\uu gc()
从lua调用。我的问题是为什么从未调用\u gc
元方法?我不理解这个问题-这不是因为luaW\u发布(L,vec)代码>被注释掉了,是吗?@JackDeeth:不,不是。即使未注释掉luaW\u release
,也不会调用\uuu gc
本身,因为我看不到MessageBox。此库实现了自己的(标准)luaW\u gc
函数,因此您的自定义\uu gc
元方法被忽略(可能是由标准方法编写的).我应该在代码的哪一部分调用luaW\u gc
?当我创建一个包含1000000个元素的向量时,内存使用量会显著增加,而不会下降。这让我觉得这些东西不是垃圾收集的。Lua使用标记和扫描收集器。换句话说,它不会因为变量超出范围而收集垃圾。否则,它不知道像Vector这样的小对象是否有一块与之相关联的、未被垃圾收集的内存。因此,您必须通过添加显式dispose()方法或强制gc来提供帮助代码>被注释掉了,是吗?@JackDeeth:不,不是。即使未注释掉luaW\u release
,也不会调用\uuu gc
本身,因为我看不到MessageBox。此库实现了自己的(标准)luaW\u gc函数,因此您的自定义\uu gc
元方法被忽略(可能是由标准方法编写的).我应该在代码的哪一部分调用luaW\u gc
?当我创建一个包含1000000个元素的向量时,内存使用量会显著增加,而不会下降。这让我觉得这些东西不是垃圾收集的。Lua使用标记和扫描收集器。换句话说,它不会因为变量超出范围而收集垃圾。否则,它不知道像Vector这样的小对象是否有一块与之相关联的、未被垃圾收集的内存。因此,您必须通过添加显式dispose()方法或强制gc来提供帮助。
CVector<double>* Vector_new(lua_State* L)
{
CVector<double>* retVec=0;
int type = lua_type(L, 1);
if(type==LUA_TTABLE)retVec=new CVector<double>(L,1);
if(type==LUA_TNUMBER){
int len = luaL_checknumber(L, 1);
retVec=new CVector<double>(len);
}
return retVec;
}
int Vector_gc(lua_State* L)
{
CVector<double>* vec = luaW_check<CVector<double> >(L, 1);
//luaW_release(L, vec);
if(vec) delete vec;
vec=0;
wxMessageBox("GC is called");
return 0;
}
static luaL_Reg Vector_table[] = {{ NULL, NULL }};
static luaL_Reg Vector_metatable[] = {
{"__gc", Vector_gc},
{ NULL, NULL }
};
int luaopen_Vector(lua_State* L)
{
luaW_register<CVector<double> >(L, "Vector", Vector_table, Vector_metatable, Vector_new);
lua_pop(L,1);
return 0;
}
for i=1,2 do local v=Vector.new(2) end