gpt4 book ai didi

c++ - .cpp 文件中类型相同但主体不同的内联函数

转载 作者:行者123 更新时间:2023-12-03 07:15:37 24 4
gpt4 key购买 nike

有点奇怪,不太实用,但我正在 cpp 中使用内联尝试一些随机的东西,我考虑尝试一下:

 inline void foo(void){static int x=0; x++; cout << x << '\n'; return;};

在另一个 .cpp 文件中我有:

 inline void foo(void){static int x=0; x=x+2; cout << x << '\n'; return;};

现在,由于某种原因(相同的函数类型/名称),但主体不同,它们都共享相同的 'x' 但它们的定义不同。我希望编译器会提示,但事实并非如此。这是为什么?

最佳答案

根据basic.def.odr#13,该程序格式不正确,无需诊断 :

  1. There can be more than one definition of a
  • inline function or variable ([dcl.inline]),

in a program provided that each definition appears in a different translation unit and the definitions satisfy the following requirements.Given such an entity D defined in more than one translation unit, for all definitions of D, or, if D is an unnamed enumeration, for all definitions of D that are reachable at any given program point, the following requirements shall be satisfied.

  • Each such definition shall consist of the same sequence of tokens, where the definition of a closure type is considered to consist of the sequence of tokens of the corresponding lambda-expression.
  1. If these definitions do not satisfy these requirements, then the program is ill-formed; a diagnostic is required only if the entity is attached to a named module and a prior definition is reachable at the point where a later definition occurs.

(强调我的)

由于示例中的函数定义不包含相同的标记序列,因此该程序格式不正确,无需诊断。

关于c++ - .cpp 文件中类型相同但主体不同的内联函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64537486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com