标签:indent 标准库 malloc ack string类 cpp name erro 说明
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;
}而STL的string在赋值之前须要调用默认的构造函数以初始化string后才干使用。如赋值、打印等操作,假设使用malloc分配内存。就不会调用string默认的构造函数来初始化结构体中的app_name字符串,因此这里给其直接赋值是错误的,应该使用new操作符。这也提示我们用C++开发程序时,就尽量使用C++中的函数,不要C++与C混合编程,导致使用混淆。比方有时候new分配的内存却用free释放。
#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; //ERROR标签:indent 标准库 malloc ack string类 cpp name erro 说明
原文地址:http://www.cnblogs.com/lxjshuju/p/6920235.html