問題描述
我一直對此很好奇 - 為什么在 C++ 中我必須從 malloc
轉換返回值,而不是在 C 中?
I have always been curious about this - why do in C++ I have to cast return value from malloc
but not in C?
以下是 C++ 中有效的示例:
Here is the example in C++ that works:
int *int_ptr = (int *)malloc(sizeof(int*));
這是 C++ 中不起作用的示例(無強制轉換):
And here is the example in C++ that doesn't work (no cast):
int *int_ptr = malloc(sizeof(int*));
我聽說在 C 中,實際上,從 malloc()
轉換輸出是一個錯誤.
I heard that in C, in fact, casting an output from malloc()
is a mistake.
有人可以評論這個話題嗎?
Can anyone comment on this topic?
推薦答案
幾點:
C 允許將 void 指針隱式轉換為任何其他對象指針類型.C++ 沒有.
C allows void pointers to be implicitly converted to any other object pointer type. C++ does not.
在 C 中轉換 malloc()
的結果將抑制有用的診斷,如果您忘記包含 stdlib.h 或沒有 malloc()
在范圍內.請記住,如果 C 看到一個沒有事先聲明的函數調用,它將假定該函數返回 int
.如果您沒有對 malloc()
的聲明并且不進行強制轉換,您將得到一個診斷結果,表明您正在嘗試分配不兼容的類型(int 到指針).如果您轉換結果,則會抑制診斷,并且可能會出現運行時問題,因為不能保證將指針值轉換為 int 并再次轉換回指針會給您一個有用的結果.
Casting the result of malloc()
in C will supress a useful diagnostic if you forget to include stdlib.h or otherwise don't have a declaration for malloc()
in scope. Remember that if C sees a function call without a prior declaration, it will assume that the function returns int
. If you don't have a declaration for malloc()
and you leave off the cast, you'll get a diagnostic to the effect that you're trying to assign incompatible types (int to pointer). If you cast the result, you supress the diagnostic and will potentially have runtime issues, since it's not guaranteed that converting a pointer value to an int and back to a pointer again will give you a useful result.
如果你在寫 C++,你應該使用 new
和 delete
而不是 malloc()
和 free()代碼>.是的,是的,是的,我聽說過人們希望他們的代碼同時編譯為 C 和 C++ 的所有原因,但是為該語言使用正確的內存管理工具的好處超過了維護兩個版本 IMO 的成本.
If you're writing C++, you should be using new
and delete
instead of malloc()
and free()
. Yeah, yeah, yeah, I've heard all the reasons why people want their code to compile as both C and C++, but the benefits of using the right memory management tool for the language outweigh the cost of maintaining two versions IMO.
注意:void *
類型是在C89標準中添加的;早期版本的 C 有 malloc()
返回 char *
,因此在這些版本中,如果您將結果分配給不同的結果,則需要 指針類型.不過,幾乎每個人都至少支持 C89 標準,因此您遇到這些舊實現之一的幾率非常非常低.
Note: the void *
type was added in the C89 standard; earlier versions of C had malloc()
return char *
, so in those versions the cast was required if you were assigning the result to a different pointer type. Almost everybody supports at least the C89 standard though, so the odds of you running into one of those older implementations is very, very low.
這篇關于為什么 C++ 需要對 malloc() 進行強制轉換,而 C 不需要?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!