string是一个无论哪个语言都有的问题
char * getstr1(){
char s[] = "test";
return s;
}
char * getstr2(){
char *s = "test";
return s;
}
这个问题考C语言里会经常碰到,getstr1中的s是堆栈上的变量,局部变量,不能返回;getstr2中的s是字符串常量,存储在静态存储区,所以可以返回。
再看一下就知道了。
#include <stdio.h>
int main(){
char *s1 = "test";
char *s2 = "test";
printf("%d\n",(s1==s2));
system("PAUSE");
}
再看看c++:
#include <string>
#include <iostream>
using namespace std;
int main(){
char *s1 = "abc";
char *s2 = "abc";
string a = "abc";
string *b = new string("abc");
const string c = "abc";
cout << boolalpha << (s1==s2) << endl;
cout << boolalpha << (s1==a) << endl;
cout << boolalpha << (s1==c) << endl;
cout << boolalpha << (&a==b) << endl;
cout << boolalpha << (&a==&c) << endl;
system("PAUSE");
}
输出结果:
true
true
true
false
false
Java中的String是非常特殊的,可以参见:http://topic.csdn.net/t/20030331/09/1597184.html
对于String我深有体会,java大量使用String消耗内存太快了。