C ++发布将char *分配给字符串

时间:2014-08-31 18:11:20

标签: c++ string memory-management char strdup

我试图找到答案但却看不到任何直接的事情。

如何在下一个代码段中释放已分配的内存:

const char* attStr = strdup(OtherCharStr); string str(attStr, strlen(attStr)); delete str; //???

2 个答案:

答案 0 :(得分:3)

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 ++使用newdelete而不是malloc()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;

我建议您阅读有关smart pointers的内容,这些内容会删除他们自动指向的对象。我离原始问题很远,但这个主题对于理解C ++的工作方式非常重要。

答案 1 :(得分:1)

您需要释放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

会发生什么