简体   繁体   English

GCC对从void *到void **的隐式转换不发出警告

[英]GCC not warning on implicit cast from void * to void **

As void * is the generic pointer, any other type can be implicitly cast to it. 由于void *是通用指针,因此可以将其他任何类型隐式转换为它。 However, void ** isn't the generic pointer to pointer thus I would expect a warning from gcc if I implicitly cast to it. 但是,void **不是通用的指针,因此如果我隐式地将其强制转换为指针,我会期望gcc发出警告。

In my code I have a function that takes a pointer to an opaque pointer (because it can be realloced and written back) as: 在我的代码中,我有一个将指针指向不透明指针的函数(因为它可以重新分配并写回),如下所示:

char *string_store(void **ctxp, const char *str);

If I call this incorrectly as: 如果我将其错误地称为:

void *context;
...
name = string_store(content, "my name");

instead of string_store(&content...) , I would expect gcc to warn about this. 而不是string_store(&content...) ,我希望gcc对此发出警告。 But it doesn't. 但事实并非如此。 I have -Wall -Wextra options to gcc. 我对gcc有-Wall -Wextra选项。

Is there a warning option to turn this on? 是否有警告选项可将其打开? I can't find it in the gcc docs. 我在gcc文档中找不到它。

As void * is the generic pointer, any other type can be implicitly cast to it. 由于void *是通用指针,因此可以将其他任何类型隐式转换为它。

You are right that void * is the generic pointer. 没错, void *是通用指针。 This means two things: 这意味着件事:

  • Any other pointer type is implicitly cast to void * ; 任何其他指针类型都隐式转换为void * ;
  • void * is implicitly cast to any other pointer type. void *被隐式转换为任何其他指针类型。

The lack of warning by GCC, therefore, is not because you are implicitly casting to void ** , but because you are implicitly casting from void * . 因此,GCC缺乏警告不是因为您隐式地将其转换 void ** ,而是因为您是隐式地将其转换 void * A warning, as you request, would be inappropriate in many cases, including this very real use case: 根据您的要求,警告在许多情况下都是不合适的,包括以下非常实际的用例:

void **ptr = malloc(sizeof *ptr);

As such, I don't believe that it is even desirable. 因此,我认为这不是可取的。 For stricter pointer conversions, use C++, where most implicit void * casts have been removed. 对于更严格的指针转换,请使用C ++,其中大多数隐式void *强制类型已被删除。

There is, apparently, the -Wc++-compat flag which will warn about this, but you may get very annoyed by it. 显然,有-Wc++-compat标志将对此发出警告,但是您可能会对此感到非常恼火。

Warn about ISO C constructs that are outside of the common subset of ISO C and ISO C++, eg request for implicit conversion from void * to a pointer to non-void type. 警告有关ISO C和ISO C ++的公共子集之外的ISO C构造,例如,请求从void *隐式转换为指向非void类型的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM