Visual Studio是否在打印函数地址时出现错误? [英] Is Visual Studio buggy in printing the function address?

查看:184
本文介绍了Visual Studio是否在打印函数地址时出现错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采取以下测试用例:

#include <iostream>

void foo()
{}

int main()
{
   std::cout << &foo << std::endl;
}

GCC 4.1.2,GCC 4.8和GCC 4.9 C ++ 11)在构建并编译时,所有提供以下输出

GCC 4.1.2, GCC 4.8 and GCC 4.9 (C++03 and C++11) all give the following output when building and then compiling:

$ g++ main.cpp -o test && ./test
main.cpp: In function 'int main()':
main.cpp:8:23: warning: the address of 'void foo()' will always evaluate as 'true' [-Waddress]
   std::cout << &foo << std::endl;
                 ^
1

这可能是因为函数指针转换为 bool (并且转换为 void *

This is supposedly because the only viable stream insertion for the function pointer is conversion-to-bool (and a cast to void* would be required to actually get an address into the stream).

但是,Microsoft Visual Studio 2012和2013会输出指针地址。

However, Microsoft Visual Studio 2012 and 2013 output a pointer address instead.

的工具链是否符合?

推荐答案

MSVC可以使函数正确运行,并执行从函数指针到 bool 如果禁用语言扩展( / Za 切换)。如果你这样做,你的代码产生以下警告(VS2013上 / W4

MSVC can be made to function correctly and perform the conversion from function pointer to bool if you disable language extensions (/Za switch). If you do that, your code produces the following warnings (at /W4 on VS2013)

1>main.cpp(8): warning C4305: 'argument' : truncation from 'void (*)(void)' to 'std::_Bool'
1>main.cpp(8): warning C4800: 'void (*)(void)' : forcing value to bool 'true' or 'false' (performance warning)

,输出为 1

此行为是 部分 p>

This behavior is documented under the Casts section


C ++编译器和C编译器都支持这些非ANSI类型转换:

...

非ANSI转换的数据指针的函数指针

Both the C++ compiler and C compiler support these kinds of non-ANSI casts:
...
Non-ANSI casts of a function pointer to a data pointer

没错,下面的行只编译 / Za disabled

Sure enough, the following line compiles only with /Za disabled

void *p = &foo;

禁用语言扩展会生成错误消息

Disabling language extensions produces the error message

1>main.cpp(8): error C2440: 'initializing' : cannot convert from 'void (*)(void)' to 'void *'
1>          There is no context in which this conversion is possible

这篇关于Visual Studio是否在打印函数地址时出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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