我应该如何在C ++中强制转换malloc的结果? [英] How should I cast the result of malloc in C++?

查看:72
本文介绍了我应该如何在C ++中强制转换malloc的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,此问题与C中的 malloc new / C ++中的智能指针。

Please note this question is not about malloc in C or malloc vs new/smart pointers in C++.

如果我在C ++中使用 malloc ,我应该使用演员表吗?以下所有工作。

If I use malloc in C++, what kind of cast should I use? The following all work.

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 ++样式强制转换,并且希望采用安全编码习惯。

I prefer to use C++ style casts in my code as much as possible and I want to adopt safe coding habits. Please advise with this in mind.

谢谢。

推荐答案

由于 malloc 返回指向 void 的指针,因此没有理由在指针上使用C ++样式转换:获得一块原始内存,并且没有任何后面的结构,因此,您可以通过添加强制类型转换来告诉编译器的唯一一件事就是您打算将该内存用于特定类型的数据。编译器必须对此表示同意,因为它没有其他信息可以再次检查您的决定。 static_cast< T> reinterpret_cast< T> 都没有提供优于C样式转换的优势,并且C风格的转换更短。

Since malloc returns a pointer to void, there is no reason to use a C++ - style cast on the pointer: you get a chunk of raw memory, with no structure behind it, so the only thing your can tell the compiler by adding a cast is that you plan to use this memory for data of a particular kind. Compiler must agree with you on that, because it has no additional information to double-check your decision. Neither static_cast<T> nor the reinterpret_cast<T> offer a particular advantage over the C-style cast, and the C-style cast is shorter.

从个人角度看,我看了很多C ++代码,但是我从未见过将C风格的转换与 malloc ,只有C风格。

From the personal perspective, I looked at a lot of C++ code, but I've never seen a C++ - style cast used with malloc, only the C-style.

这篇关于我应该如何在C ++中强制转换malloc的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆