C->C++ Automatically cast void pointer into Type pointer in C++ in #define in case of type is not given (C-style) [MSVS]

前端 未结 4 929
暗喜
暗喜 2021-02-15 15:00

Hi!

I\'ve used the following C macro, But in C++ it can\'t automatically cast void* to type*

4条回答
  •  抹茶落季
    2021-02-15 15:39

    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:

    #define MALLOC_SAFE(var,size)  {  \
        (* (void **) & (var)) = malloc(size); \
        if ( ! (var) ) goto error;    \
        }
    

    Yeah... I know. It's sick, and throws type-safety right out the window. But a straight ((void *)(var))= cast wouldn't always work.

提交回复
热议问题