如何正确寻址-Wcast-qual
我有一个 const char *
类型的变量 k
,并且在 glib 中
void g_hash_table_replace(GHashTable *hash_table,
gpointer key,
gpointer value);
定义了一个带有原型 gpointer
的函数,正如
typedef void* gpointer;
我所知道的那样事实上,在这种情况下,可以将 k
作为 g_hash_table_replace
中的键传递,但是 gcc 给了我错误,
service.c:49:3: warning: passing argument 2 of ‘g_hash_table_replace’ discards ‘const’ qualifier from pointer target type [enabled by default]
/usr/include/glib-2.0/glib/ghash.h:70:13: note: expected ‘gpointer’ but argument is of type ‘const char *’
这是 gcc 4.6.0 的错误。在 4.5.0 及更早版本中,简单地转换为 (char *) 就足以抑制此警告,但 gcc 似乎变得“更聪明”。我已经尝试过 (char *)(void *)k
,但它仍然知道该变量最初是 const
。在不调用 k
上的 strdup(3)
的情况下,消除此警告的最佳方法是什么?
I have a variable k
of type const char *
, and a function in glib with the prototype
void g_hash_table_replace(GHashTable *hash_table,
gpointer key,
gpointer value);
gpointer
is defined simply as
typedef void* gpointer;
I know that in this case it is, in fact, okay to pass in k
as the key in g_hash_table_replace
, however gcc gives me the error
service.c:49:3: warning: passing argument 2 of ‘g_hash_table_replace’ discards ‘const’ qualifier from pointer target type [enabled by default]
/usr/include/glib-2.0/glib/ghash.h:70:13: note: expected ‘gpointer’ but argument is of type ‘const char *’
this is with gcc 4.6.0. With 4.5.0 and earlier, a simple cast to (char *) sufficed to supress this warning, but gcc seems to have gotten 'smarter'. I've tried (char *)(void *)k
, but it still knows that the variable was originally const
. What is the best way to silence this warning without calling strdup(3)
on k
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我刚刚用 gcc 4.6.1 尝试过。
如果没有强制转换,错误将如您上面所描述的那样。但是,如果我首先将
const char*
转换为intptr_t
(如上所示),则警告将被抑制。您能否确认我的代码示例仍然遇到该错误?I just tried this with gcc 4.6.1.
Without casts, the error is as you describe above. But if I cast the
const char*
tointptr_t
first as shown above, the warning is suppressed. Can you confirm that you still experience the error with my code sample?