請注意這個問題不是關於C的malloc
或malloc
vs new
/C++中的智能指針。我應該如何在C++中投射malloc的結果?
如果我在C++中使用malloc
,應該使用什麼類型的轉換?以下全部工作。
int *a = (int *)malloc(sizeof (int));
int *b = static_cast<int *>(malloc(sizeof (int)));
int *c = reinterpret_cast<int *>(malloc(sizeof (int)));
活生生的例子: http://ideone.com/lzfxcm
我更喜歡使用C++風格轉換在我的代碼儘可能地和我要採取安全的編碼習慣。請記住這個建議。
謝謝。
的malloc的,一個C風格的類型轉換並不比reintprerpt_cast更不安全。 – tenfour
是安全的,你應該使用新的而不是malloc –
@claptrap我明確指出這個問題不是關於malloc vs new。有時malloc在C++中使用。它發生了。 –