我是否在 C++ 中转换 new 的结果?
Do I cast the result of new in C++?
在问题 Do I cast the result of malloc? 的答案中提到我不需要也不应该在 C 中转换 malloc()
的返回 void
指针。
但是 C++ 中的 new
运算符如何呢?
是否有明确的理由只做:
int *p_rt = new int;
而不是
int *p_tr = (int*) new int;
或者我可以做演员吗?
new T
returns T*
,所以不用强制转换:
T* p = new T;
另一方面,malloc
的 return 类型是 void*
,因此在 C++ 中必须转换为 T*
:
T* p = static_cast<T*>(malloc(sizeof(T));
另请注意,如 , new T
not only allocates the memory for the new object, but also constructs the object in that memory. malloc
doesn't do it, so you must construct the object manually with placement new
中所指出的那样。
Is there an explicit reason to do:
int *p_rt = new int;
instead of
int *p_rt = (*int) new int;
是的,使用第一个是有原因的。重新解释转换会禁用类型诊断,并且通常会导致错误。如果可能的话,你应该避免使用它们。将指针转换为同一类型没有任何优势。
P.S。您尝试的转换在语法上是错误的。
与 malloc() 不同,c++ 中的新运算符已经 return 分配类型的指针。所以没必要投。在 c 中,类型检查没有那么严格,因此您不必将 void* 强制转换为您想要的类型。数据将自动解释为您指定的类型。另一方面,如果你在 C++ 中使用 malloc 进行分配,你应该转换(否则你可能会收到编译器警告)。
对问题进行的编辑已转换为答案
编辑:我之所以感到困惑,是因为我在 http://www.cplusplus.com/reference/new/operator%20new/ 阅读了 void* operator new (std::size_t size);
,并认为 new
会 return void*
。
感谢@Someprogrammerdude 和@UlrichEckhardt 的评论,我发现 new
运算符和 operator new
是两个不同的东西,new
与 [=16 相对=] 显式 return 是相应类型的指针。
对于以后遇到这个问题的大家,我想提供一个link给明确说明两者区别的问题:Difference between 'new operator' and 'operator new'?
C 允许编译器执行从 void*
指针到另一种指针类型的隐式转换,因此 malloc()
的 return 值不需要显式类型转换在 C.
C++ 不允许编译器执行这种隐式转换,因此 malloc()
的 return 值必须在 C++ 中显式类型转换。
在 C++ 中 new
的 return 值不需要类型转换,因为它 return 是它创建的类型的指针,它不 return一个void*
指针。
在问题 Do I cast the result of malloc? 的答案中提到我不需要也不应该在 C 中转换 malloc()
的返回 void
指针。
但是 C++ 中的 new
运算符如何呢?
是否有明确的理由只做:
int *p_rt = new int;
而不是
int *p_tr = (int*) new int;
或者我可以做演员吗?
new T
returns T*
,所以不用强制转换:
T* p = new T;
另一方面,malloc
的 return 类型是 void*
,因此在 C++ 中必须转换为 T*
:
T* p = static_cast<T*>(malloc(sizeof(T));
另请注意,如 new T
not only allocates the memory for the new object, but also constructs the object in that memory. malloc
doesn't do it, so you must construct the object manually with placement new
中所指出的那样。
Is there an explicit reason to do:
int *p_rt = new int;
instead of
int *p_rt = (*int) new int;
是的,使用第一个是有原因的。重新解释转换会禁用类型诊断,并且通常会导致错误。如果可能的话,你应该避免使用它们。将指针转换为同一类型没有任何优势。
P.S。您尝试的转换在语法上是错误的。
与 malloc() 不同,c++ 中的新运算符已经 return 分配类型的指针。所以没必要投。在 c 中,类型检查没有那么严格,因此您不必将 void* 强制转换为您想要的类型。数据将自动解释为您指定的类型。另一方面,如果你在 C++ 中使用 malloc 进行分配,你应该转换(否则你可能会收到编译器警告)。
对问题进行的编辑已转换为答案
编辑:我之所以感到困惑,是因为我在 http://www.cplusplus.com/reference/new/operator%20new/ 阅读了 void* operator new (std::size_t size);
,并认为 new
会 return void*
。
感谢@Someprogrammerdude 和@UlrichEckhardt 的评论,我发现 new
运算符和 operator new
是两个不同的东西,new
与 [=16 相对=] 显式 return 是相应类型的指针。
对于以后遇到这个问题的大家,我想提供一个link给明确说明两者区别的问题:Difference between 'new operator' and 'operator new'?
C 允许编译器执行从 void*
指针到另一种指针类型的隐式转换,因此 malloc()
的 return 值不需要显式类型转换在 C.
C++ 不允许编译器执行这种隐式转换,因此 malloc()
的 return 值必须在 C++ 中显式类型转换。
在 C++ 中 new
的 return 值不需要类型转换,因为它 return 是它创建的类型的指针,它不 return一个void*
指针。