我需要照顧內存分配,範圍和刪除關於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