gpt4 book ai didi

c++ - Tcl_Format 内存使用

转载 作者:行者123 更新时间:2023-11-30 02:26:52 25 4
gpt4 key购买 nike

这是一个用 C(++) 编写的 TCL 扩展程序(这里是 C++ 并不重要——我只使用 std::vector )。我用 Tcl_Format创建一个新的格式化字符串。如果我不使用 Tcl_DecrRefCount ,Xcode 报告每次调用此外部过程时使用的内存越来越多:

int TclME::vTestExt(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj* const objv[])
{
Tcl_Obj *resultPtr, *item[1], *itemFormatted;
size_t N;
std::vector<long> v;
populate_v(v);
N = v.size();
resultPtr = Tcl_NewListObj(0, NULL);
for (long i = 0; i < N; ++i) {
item[0] = Tcl_NewLongObj(v[i]);
printf("item[0] ref %i, sh %i; ", item[0]->refCount, Tcl_IsShared(item[0]));
itemFormatted = Tcl_Format(interp, "#%06X", 1, item);
// With Tcl_DecrRefCount commented out, there is a memory leak
printf("\tref %i, sh %i; ", item[0]->refCount, Tcl_IsShared(item[0]));
Tcl_DecrRefCount(item[0]);
printf("\tref %i, sh %i\n", item[0]->refCount, Tcl_IsShared(item[0]));

Tcl_ListObjAppendElement(interp, resultPtr, itemFormatted);
}
Tcl_SetObjResult(interp, resultPtr);
return TCL_OK;
}

void populate_v(std::vector<long> &v)设置 vector 项。

输出是item[0] ref 0, sh 0; ref 0, sh 0; ref -1, sh 0 , 所以我不希望不得不调用 Tcl_DecrRefCount手动。

我错过了什么?

最佳答案

当您创建一个新的 TCL 对象时,它的引用计数为 0。

当引用计数器下降到 0 时,任何 TCL 对象都会被释放。因此,干净的方法是在创建对象后首先增加引用计数器然后在不再使用时再次递减(例如在调用 Tcl_Format() 之后)。

在上面的特殊情况下,您可以使用 Tcl_ObjPrintf() 来避免这个问题:

...
for (long i = 0; i < N; ++i) {
Tcl_ListObjAppendElement(interp, resultPtr, Tcl_ObjPrintf("#%06X", v[i]));
}
...

关于c++ - Tcl_Format 内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42347348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com