c++結構體中包含類對象成員的問題

今天寫代碼遇到一個問題。以下的結構體:數組

struct A
{
  string str;
  int data;
//....
};

在代碼中須要動態爲這個結構體分配內存,習慣性的:

A *a = (A *)malloc(sizeof(A));

而後爲 str 賦值輸出:函數

a->str = "testdata";
cout << a->str << endl;

結果直接 Segment Fault!了。

google下,原來是調用 malloc 並不調用string的構造函數,致使 str 未初始化。要避免這樣的問題,用 C 的方式可使用字符數組(char *str),或者在 C++裏這樣使用:google

一、A *a = new A; //使用 new 會調用成員的構造函數
   //。。。
   delete a;

或者(待驗證)spa

二、void *v = malloc(sizeof(A));
   A *a = new (v)A;
   //......
   a->~A();
   free(v);

 ref: http://stackoverflow.com/questions/7609981/possible-memory-leak-with-malloc-struct-stdstring-and-freecode

相關文章
相關標籤/搜索