c++ - 为什么获取已声明函数的地址才有效?

标签 c++ function-pointers function-declaration addressof function-definition

我问了一个question here关于获取函数地址是否强制编译所述函数,特别是关于 Substitution-Failure-Is-Not-An-Error。可以找到最直接的答案 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.

但我测试过的所有编译器都表明这是完全可行的:

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

Live Example

这不合法吧?但如果不是,为什么要构建它?

最佳答案

来自 [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-used,但没有定义(大概 - 否则问题是没有意义的)。该程序格式错误,但由于不需要诊断,因此编译有效。

通常,是链接器发现了定义的缺失,而不是编译器,因为定义很容易出现在不同的翻译单元中。典型示例试图将缺少定义的 static const int 传递到对 std::max()std::min()< 的调用中

关于c++ - 为什么获取已声明函数的地址才有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38437533/

相关文章:

c++ - 结构成员变量不变

c++ - 调用 void 函数时 cout 没有输出

c++ - 将函数传递给函数并使用头文件时出错

c++ - 内联函数原型(prototype) vs 常规声明 vs 原型(prototype)

c - 函数声明与原型(prototype)的替代 (K&R) C 语法

c++ - 为什么引用类型成员的默认初始化会导致编译器警告?

c++ - boost::gregorian input_facet 意外结果

c - 函数指针赋值

c++11 - 函数指针的编译时选择

C++ - 声明函数 'static' 与形式 'const int function_name() const'