这是 this question 的跟进.
正如对答案的评论中提到的:
An inline variable has the property that - It has the same address in every translation unit. [...] Usually you achieved that by defining the variable in a cpp file, but with the inline specifier you can just declare/define your variables in a header file and every translation unit using this inline variable uses exactly the same object.
此外,从答案本身来看:
While the language does not guarantee (or even mention) what happens when you use this new feature across shared libraries boundaries, it does work on my machine.
换句话说,当涉及共享库时,是否保证内联变量跨边界唯一是不清楚的。有人根据经验证明它在某些平台上有效,但这不是正确的答案,它可能会破坏其他平台上的一切。
当跨边界使用时,是否可以保证内联变量的唯一性,或者它只是一个我不应该依赖的实现细节?
最佳答案
这就是我对标准的解释。根据basic.link/1 :
A program consists of one or more translation units linked together.
它没有提及静态链接或动态链接。程序是链接在一起的翻译单元。链接是否分两步完成并不重要(首先创建一个 .dll/.so,然后动态链接器将所有动态库 + 可执行文件链接在一起)。
因此,根据我的解释,程序是动态链接还是静态链接并不重要,实现的行为应该相同:类静态变量应该是唯一的(无论它是否内联)。
在 Linux 上,这是真的。
在 Windows 上,这并非在所有情况下都有效,因此根据我的解释,它在这些情况下违反了标准(如果您创建一个单独的 .dll,其中包含静态、非内联变量和所有其他 . dll 和 exe 引用此变量,它有效)。
关于c++ - 行内变量是否跨界唯一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51524198/