c++ - 取消分配从函数返回的 char*

标签 c++ memory-management char

当我创建一个返回 char* 或 const char* 的函数时,是否假定调用函数在完成返回值时必须释放返回值?否则,它将如何被释放?我正在寻找其他一些调用返回 char* 的函数的代码,并且调用函数中没有 delete 语句。示例:

char* foo();

void bar()
{
    char* result = foo();
    //I should have "delete result" here right?
}

编辑:

所以在我的应用程序中,这里是 foo:

LPTSTR GetTempPath(LPCTSTR fileName)
{   
    LPTSTR tempPath = new TCHAR[500];
    GetTempPath(500,tempPath);
    printf("Temp Path %ls\n",tempPath);
    PathAppend(tempPath, fileName);
    _tprintf(_T("New temp path: %s\n"), tempPath);
    return tempPath;
}

如果没有新的 TCHAR,我不确定如何写这个。 我假设这必须删除?有没有更好的写法?

最佳答案

如果您使用的是 C++ 而不是 C,您应该使用 std::string 来解决这个问题。

关于c++ - 取消分配从函数返回的 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16970258/

相关文章:

c++ - 我应该如何在 C++ 中转换 malloc 的结果?

c# - 当我们在 C# 中重新分配数组时,数组的值是否被破坏?

c++ - 将 Const Char 附加到 Char* C++

c - 将字符串放入C中的二维字符数组

c - 关于在 C 中使用扩展符号将 char 转换为 int

c++ - 阅读 Effective、More Effective 和 Effective Modern C++(和 STL)的首选顺序是什么?

c++ - 在 C++ 构造器中管理 bad_alloc 异常

c++ - C++中的拆分函数

linux - libc内存管理

java - Java/Scala 中可以禁用边界检查吗?