我需要照顾内存分配,范围和删除关于C++“string”对象吗?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:我不需要 '删除' S2。 func3:我需要'删除s3'吗?
顺便说一句,func1是否正确?字符内存内容在离开func1范围后仍然可用吗?如果是的话,我应该删除它,当我不再需要它了吗?
http://stackoverflow.com/questions/2579874/lifetime-of-a-const-string-literal-returned-by-a-function – elgcom 2010-10-06 14:14:51
http://stackoverflow.com/questions/267114/scope-of -string-literals – elgcom 2010-10-06 14:15:31