防止从假到指针的无提示强制转换 [英] Prevent silent cast from false to pointer

查看:82
本文介绍了防止从假到指针的无提示强制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能

void foo(int *bar)
{}

现在,如果我这样调用foo,Visual Studio 2012将很高兴且不会发出警告:

Visual Studio 2012 will now happily and without warnings compile if I call foo like this:

int main()
{
  foo(false);
  return 0;
}

但是如果我将foo(false)更改为foo(true)却收到错误消息:

If I however change foo(false) to foo(true) than I get an error:

1>main.cpp(132): error C2664: 'foo' : cannot convert parameter 1 from 'bool' to 'int *'
1>          Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast

有什么想法可以确保在传递false时也得到错误提示吗?我唯一的想法是添加第二个私有函数"void foo(bool bar)".然后,我确实得到了想要的错误,指出foo(bool bar)是私有的.但这仅在从类外部调用foo并且使我的界面混乱时才有效.

Any idea how I can make sure that I get an error when passing false, too? My only idea is to add a second private function "void foo(bool bar)". Then I indeed get the desired error stating that foo(bool bar) is private. But this only works when foo is called from outside the class and it clutters my interface.

推荐答案

首先,为何接受false但不接受true:文字错误将被解释为整数0和文字将转换为任何类型的空指针.另一方面,true不能转换为指针类型,因为它会转换为整数1.

First, as to why it accepts false but not true: The literal false will be interpreted as the integral 0 and a literal 0 will convert to a null pointer of any type. true on the other hand cannot be converted to a pointer type as it converts to an integral 1.

关于如何解决您的问题的方法:只要您不实现私有重载,带有额外的bool重载的方法对于公共和非公共调用方都可以正常工作.在这种情况下,公共调用者将获得编译错误,而成员调用者将获得链接程序错误.

As to how to solve your problem: Your approach with an extra bool overload will work fine for both public and non-public callers as long as you don't implement the private overload. In that case public callers will get a compile error and member callers will get a linker error.

但是,您可能还希望考虑其他事项.

However, you may wish to consider additional things as well.

您的函数是否需要接受空指针?如果不是,请将其更改为通过引用接受,然后问题就消失了.

Does your function need to accept null pointers? If not, change it to accept by reference instead and the problem just goes away.

如果您的函数确实确实需要接受空指针,那么在这种情况下,我建议您只信任您的用户正确调用它,而不要弄乱您的界面以防止任何可能的滥用.

If your function really does need to accept null pointers then I would suggest in this case to just trust your users to call it correctly instead of cluttering your interface trying to prevent every possible misuse.

这篇关于防止从假到指针的无提示强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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