C->C++自动将 void 指针转换为 C++ 中的 Type 指针在 #define 中,如果未给出类型(C 风格)[MSVS]
嗨!
我使用了以下C宏,但在C++中它无法自动转换void*
输入*
。
#define MALLOC_SAFE(var, size) { \
var = malloc(size); \
if (!var) goto error; \
}
我知道,我可以这样做:
#define MALLOC_SAFE_CPP(var, type, size) { \
var = (type)malloc(size); \
if (!var) goto error; \
}
但我不想重写使用 MALLOC_SAFE
的大部分代码。
有什么方法可以在不向宏提供类型的情况下执行此操作吗?也许一些 MSVC 2005 #pragma
/__declspec
/other ?
ps:我不能使用C编译器,因为我的代码是大型项目的一部分(数百个模块之一)。现在是在 C++ 上。我知道,我可以单独构建我的代码。但它是旧代码,我只想快速移植它。
问题是关于 void* 转换;)如果不可能,我将用 MACRO_SAFE_CPP 替换 MACRO_SAFE
谢谢!
Hi!
I've used the following C macro, But in C++ it can't automatically cast void*
to type*
.
#define MALLOC_SAFE(var, size) { \
var = malloc(size); \
if (!var) goto error; \
}
I know, I can do something like this:
#define MALLOC_SAFE_CPP(var, type, size) { \
var = (type)malloc(size); \
if (!var) goto error; \
}
But I don't want to rewrite a big portion of code, where MALLOC_SAFE
was used.
Is there any way to do this without giving the type to the macro? Maybe some MSVC 2005 #pragma
/__declspec
/other ?
p.s.: I can't use C compiler, because my code is part (one of hundreds modules) of the large project. And now it's on C++. I know, I can build my code separately. But it's old code and I just want to port it fast.
The question is about void* casting ;) If it's not possible, I'll just replace MACRO_SAFE with MACRO_SAFE_CPP
Thank You!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为了让 James 的答案更加肮脏,如果你没有 decltype 支持,你也可以这样做:
然后:
除了邪恶之外,不要将它用于任何目的。
To makes James' answer even dirtier, if you don't have
decltype
support you can also do this:Then:
Don't use it for anything but evil.
我不建议这样做;这是糟糕的代码,如果您使用的是 C,则应该使用 C 编译器对其进行编译(或者,在 Visual C++ 中,作为 C 文件)
如果您使用的是 Visual C++,则可以使用
decltype:
I do not recommend doing this; this is terrible code and if you are using C you should compile it with a C compiler (or, in Visual C++, as a C file)
If you are using Visual C++, you can use
decltype
:例如,像这样:
For example, like this:
是否有人直接将您的参数强制转换为 SAFE_MALOC() 的 var ?我的意思是,malloc() 返回一个指针。你将它存储在接受指针的地方...其他人已经指出了各种整洁的类型安全的东西...我只是想知道为什么这不起作用:
是的...我知道。它很恶心,而且把类型安全抛到了九霄云外。但直接的 ((void *)(var))= 转换并不总是有效。
Is there a reason nobody just casts var, your argument to SAFE_MALOC()? I mean, malloc() returns a pointer. You're storing it somewhere that accepts a pointer... There are all sorts of neat type-safe things that other folks have already pointed out... I'm just wondering why this didn't work:
Yeah... I know. It's sick, and throws type-safety right out the window. But a straight ((void *)(var))= cast wouldn't always work.