c++ - 对内联函数有不同的定义是未定义的行为吗?

标签 c++ inline undefined-behavior function-prototypes

最少的代码:

// --------inline.h--------
struct X { 
  static inline void foo ();
};   
#ifdef YES
inline void X::foo () { cout << "YES\n"; }
#else
inline void X::foo () { cout << "NO\n"; }
#endif

// --------file1.cpp--------
#define YES    // <---- 
#include"inline.h"
void fun1 ()
{
  X::foo();
}

// --------file2.cpp--------
#include"inline.h"
void fun2 ()
{
  X::foo();
}

如果我们调用fun1()fun2(),那么它们将分别打印YESNO ,这意味着它们引用相同 X::foo() 的不同函数体。

不管这是否应该编码,我的问题是:
这是明确定义还是未定义的行为?

最佳答案

是的,这是未定义的行为。

引用:

C++03 标准:

7.1.2 函数说明符 [dcl.fct.spec]
第 4 段:

An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case (3.2). [Note: a call to the inline function may be encountered before its definition appears in the translation unit. ] If a function with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required. An inline function with external linkage shall have the same address in all translation units. A static local variable in an extern inline function always refers to the same object. A string literal in an extern inline function is the same object in different translation units.

注意:3.2指的是一个定义规则,其中规定:

3.2 一条定义规则[basic.def.odr]
第 1 段:

No translation unit shall contain more than one definition of any variable, function, class type, enumeration type or template.

关于c++ - 对内联函数有不同的定义是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11200805/

相关文章:

c++ - 判断是否有为特定类型的参数定义的重载函数

c++ - 在函数参数未定义行为中使用赋值运算符吗?

javascript - 删除 HTML 元素的内联 css

c++ - LNK2001 只有一些内联函数没有解决?

c - 为什么这些构造使用增量前和增量后未定义的行为?

c - 返回复合文字

c++ - 获取 Cstrings 的控制台输入

C++ unordered_map初始化底层会发生什么

c++ - "Inverse SFINAE"避免模棱两可的过载

css - 内联问题将自定义 style_format 添加到 tinymce