我试图找到答案,但看不到任何直接的东西。
如何在下一个代码段中释放分配的内存:
const char* attStr = strdup(OtherCharStr);
string str(attStr, strlen(attStr));
delete str; //???
我试图找到答案,但看不到任何直接的东西。
如何在下一个代码段中释放分配的内存:
const char* attStr = strdup(OtherCharStr);
string str(attStr, strlen(attStr));
delete str; //???
C++ 使用称为RIAA - Resource Acquisition Is Initialization的成语。这意味着对象的生命周期是由变量范围驱动的。
{
std::string s("foo"); // variable s declaration and string initialization
do_some_stuff(s);
// end of scope of variable s - it is destroyed here
// no need to free(s) or whatever
}
// variable s and the string doesn't exist here, no memory for it is allocated
这仅适用于正确维护其资源的 C++ 对象(在析构函数中释放它们)。简单的指针不会这样做 - 你必须自己释放它们:
const char *attStr = strdup(...);
// do something with attStr
free(attStr); // because strdup() documentation says you should free it with free()
另请注意,C++ 使用new
anddelete
而不是malloc()
and free()
:
std::string *strPointer = new std::string(...);
// RIAA doesn't work here, because strPointer is just plain pointer,
// so this is the case when you need to use free() or delete
delete strPointer;
我建议阅读一些有关智能指针的内容,这些指针会自动删除它们指向的对象。我与最初的问题相去甚远,但这个主题对于理解 C++ 的工作原理很重要。
您需要释放 attStr 而不是单独释放其资源的 c++ 字符串。
void func()
{
const char* attStr = strdup(OtherCharStr);
string str(attStr, strlen(attStr));
free(attStr);
}//here str will release its own resources
你也可以做 string str = OtherCharStr; 就是这样。只检查 OtherCharStr 发生了什么