在 C++ 中全局初始化类的正确方法

Jos*_*osh 2 c++ static initialization one-definition-rule

我知道 global 不好,但作为一种实践,这是初始化在多个目标文件之间使用的全局类的正确方法吗?

标题 1.h

class test {
 int id;
 public:
 test(int in){
   id = in;
 }
 int getId(){
  return id;
 }
};

extern test t;
Run Code Online (Sandbox Code Playgroud)

文件 1.cc :

#include <iostream>
#include "1.h"

int main(){
 std::cout << t.getId() << std::endl;
 return 0;
}
Run Code Online (Sandbox Code Playgroud)

文件 2.cc:

#include "1.h"

test t(5);
Run Code Online (Sandbox Code Playgroud)

现在,如果不是extern我在标题中static全局使用该方法static test t(0);呢?

如果我错了,请纠正我,但这会编译得很好,但是我t在两个目标文件和最终二进制文件中都会有 2 个不同的不相关副本?那不好吗?或者链接器是否对其进行排序以消除多个副本?

Tan*_*dar 5

有全局实例,而不是全局类。

您拥有的是一个全局实例。是的,这听起来是对的,直到您获得多个相互依赖的全局实例。然后真正的乐趣将开始。