C++开发的项目难免会用到STL的string,使用管理都比char数组(指针)方便的多,但在得心应手的使用过程中也要警惕几个小陷阱,避免我们项目出bug却迟迟找不到原因。
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
struct flowRecord
{
string app_name;
struct flowRecord *next;
};
int main() {
flowRecord *fr = (flowRecord*)malloc(sizeof(flowRecord));
fr->app_name = "hello";
cout << fr->app_name << endl;
return 0;
}#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Alexia";
const char *str = s.c_str();
cout << str << endl;
s[1] = ‘m‘;
cout << str << endl;
return 0;
}string s("hello");
cout<<s.size()<<endl; //OK
cout<<"hello".size()<<endl; //ERROR
cout<<s+"world"<<endl; //OK
cout<<"hello"+"world"<<endl; //ERRORC++ string中的几个小陷阱,你掉进过吗?,布布扣,bubuko.com
原文地址:http://blog.csdn.net/lanxuezaipiao/article/details/24885811