Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 永远不会调用Lua\uu gc元方法_C++_Lua - Fatal编程技术网

C++ 永远不会调用Lua\uu gc元方法

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

我有一个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(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