【发布时间】:2011-04-21 20:32:17
【问题描述】:
我是否需要处理由文字分配的 C++ 字符串的内存分配、范围和删除?
例如:
#include <string>
const char* func1() {
const char* s = "this is a literal string";
return s;
}
string func2() {
std::string s = "this is a literal string";
return s;
}
const char* func3() {
std::string s = "this is a literal string";
return s.c_str();
}
void func() {
const char* s1 = func1();
std::string s2 = func2();
const char* s3 = func3();
delete s1; //?
delete s3; //?
}
-
func2:我不需要delete s2。 -
func3:需要delete s3吗?
func1 正确吗?字符记忆内容离开func1 的范围后是否仍然可用?如果是的话,当我不再需要它时,我应该删除它吗?
【问题讨论】: