为什么采取被声明的函数的地址只工作? [英] Why is Taking the Address of a Function That is Declared Only Working?
问题描述
我在这里问了一个问题关于是否获取函数的地址强制编译所述函数具体使用关于替代故障是非错误的。对此的最直接的回答可以在此处找到:
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:
非正式地,如果一个对象的地址被采用,或者一个引用绑定到一个对象,则该对象被odr使用,并且一个函数被odr使用,如果一个函数调用它被做或它的地址被采取。如果对象或函数是odr使用的,它的定义必须存在于程序中的某个位置;
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;
这不合法吗?
推荐答案
从 [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
是odr使用,有一个定义(大概 - 否则的问题是模糊)。
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.
通常情况下,链接器捕获的是缺少定义,而不是编译器,因为定义可以容易地出现在不同的翻译单元中。规范的例子是尝试传递一个 static const int
,它缺少一个定义到 std :: max()
或 std :: min()
。
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()
.
这篇关于为什么采取被声明的函数的地址只工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!