【发布时间】:2010-11-28 18:56:09
【问题描述】:
各位,我需要一点技术帮助。 我在 C++ 中工作,没有太多的工作经验,但对这门语言有所了解。我需要使用 C 风格的字符串(char 数组),但我需要在堆上分配它。
如果你看一下这段非常简单的代码:
#include <iostream>
using namespace std;
char* getText()
{
return "Hello";
}
int main()
{
char* text;
text = getText();
cout << text;
//delete text; // Calling delete results in an error
}
现在,我假设“Hello”字符串在堆栈上分配,在 getText() 中,这意味着一旦 getText 返回,指针就会“浮动”,对吗?
如果我是对的,那么将“Hello”放在堆上的最佳方法是什么,以便我可以在 getText 之外使用该字符串并在需要时在指针上调用 delete?
【问题讨论】:
标签: c++