我是否在C ++中强制转换new的结果?

问题描述 投票:-2回答:1

在回答Do I cast the result of malloc?的问题时,我不需要也不应在C中强制转换返回的voidmalloc()指针。

但是C ++中的new运算符如何?


是否有明确的理由要做[[仅:

int *p_rt = new int;
而不是

int *p_rt = (*int) new int;

或者我可以做演员吗?
c++ casting new-operator
1个回答
3
投票

malloc的返回值是void*,因此必须在C ++中强制转换为T*

T* p = static_cast<T*>(malloc(sizeof(T));

2
投票
int *p_rt = new int;
代替

int *p_rt = (*int) new int;

是的,有理由使用第一个。重新解释强制类型转换会禁用类型诊断,并经常导致错误。您应尽可能避免使用它们。将指针强制转换为相同类型没有优势。

P.S。您尝试的强制转换在语法上是错误的。

© www.soinside.com 2019 - 2024. All rights reserved.