【问题标题】:Proper memory cleanup with c_str() and const char *使用 c_str() 和 const char * 进行适当的内存清理
【发布时间】:2024-01-20 05:29:01
【问题描述】:

我有一个接受 (char* const*) 的函数。我提供的数据在 std::string 中。所以我正在这样做:

void blahblah(std::string str)
{
   const char * cc = str.c_str();
   ConstCharFunction(&cc);
}

这很好用。我的问题是我是否需要清理 const char ala 使用的内存:

delete cc;

或者 cc 只是一个指向 std:string 中 mem 位置的指针...

【问题讨论】:

  • 如果您不修改它,为什么要将std::string 作为副本传递?

标签: c++ memory-management stdstring const-char


【解决方案1】:

它是一个指向在 std::string 中分配的内存的指针。当 std::string 超出范围时,内存被释放。之后千万不要紧握指针!

【讨论】:

【解决方案2】:

不,您不需要delete cc。它确实是std::string 对象持有的指针。

here

程序不得更改此序列中的任何字符。

返回的指针指向字符串对象当前用来存储符合其值的字符的内部数组。

请注意,c_str() 返回的指针可能会因调用字符串的修改方法而失效。

【讨论】:

    最近更新 更多