我有一个非常简单的代码片段,包含2个结构和一个动态分配.程序在"nume"初始化时崩溃.
typedef struct{
int key;
string name;
} TElement;
typedef struct nod {
int cheie;
string nume;
struct nod *stg, *dr;
} NOD;
Run Code Online (Sandbox Code Playgroud)
当我尝试这样做
void ABC::inserare_element(TElement e){
NOD *p, *q;
int n;
/* construction nod p*/
n=sizeof (NOD);
p=(NOD*)malloc(n);
p->cheie = e.key;
p->nume = e.name; // on this line the program crashes
Run Code Online (Sandbox Code Playgroud)
谢谢
malloc()将不会调用构造函数NOD,这意味着将不会调用构造函数,nume从而导致尝试在未构造std::string::operator=/未初始化的情况下std::string使用:use new.