Why is Taking the Address of a Function That is Declared Only Working?

痴心易碎 提交于 2019-12-02 20:06:31

问题


I've asked a question here about whether taking the address of a function forces the compilation of said function specifically with regard to Substitution-Failure-Is-Not-An-Error. The most direct answer to this can be found here:

Informally, an object is odr-used if its address is taken, or a reference is bound to it, and a function is odr-used if a function call to it is made or its address is taken. If an object or a function is odr-used, its definition must exist somewhere in the program; a violation of that is a link-time error.

But all the compilers I've tested show this as perfectly doable:

void foo(int);
auto bar = &foo;

Live Example

This isn't legal is it? But if not, why is it building?


回答1:


From [basic.def.odr]:

Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required.

foo is odr-used, but doesn't have a definition (presumably - otherwise the question is moot). The program is ill-formed, but since no diagnostic is required, it's valid to compile.

Typically, it's the linker that catches the lack of definition - not the compiler, since the definition could easily appear in a different translation unit. The canonical example being trying to pass a static const int which lacks a definition into a call to std::max() or std::min().




回答2:


Your example is working because the address is never used, so the linker never searches for the symbol.

If you try to print bar, the linking fails.

void foo(int);
auto bar = &foo;
cout << (void*) bar;

http://ideone.com/97Eo6Z



来源:https://stackoverflow.com/questions/38437533/why-is-taking-the-address-of-a-function-that-is-declared-only-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!