我需要处理关于c ++"string"对象的内存分配,范围和删除吗?
例如:
#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; //?
}
Run Code Online (Sandbox Code Playgroud)
func2:我不需要'删除's2.func3:我需要'删除s3'吗?
顺便说一下,func1是否正确?离开func1范围后,字符内存内容是否仍然可用?如果是,我不再需要它时应该删除它吗?