首页 > 解决方案 > 为什么具有静态存储持续时间的同一个内联变量在包含在由 vs2017 编译的两个翻译单元中时会构造和破坏两次

问题描述

“test.hpp”定义如下:

#include <iostream>
class test{
public:
  test(){
   std::cout<<"constructor"<<std::endl;
  }
  ~test(){
   std::cout<<"destructor"<<std::endl;
  }
};
class test_content{
public:
  inline static test test_gobal;
};

“a.cpp”定义如下:

#include "test.hpp"

“b.cpp”定义如下:

#include <iostream>
#include "test.hpp"
int main(){

}

和上面一样,在两个翻译单元中包含“test.hpp”,通过vs2017版本15.9.21编译这些代码,结果会打印“constructor”和“destructor”两次,有没有引用谈谈如何内联构造或破坏当它包含在多个翻译单元中时变量?我还没有找到关于这个的这些 qoutes。或者它是一个 vs2017 错误,不管这个引用是什么?

标签: c++visual-studio-2017c++17language-lawyer

解决方案


好吧,首先,我不清楚你甚至可以 std::cout在作为静态初始化的一部分执行的构造函数中使用。但是除了这个 - 给定这个程序时,clang和gcc:

#include <stdio.h>
struct test {
  test() { printf("ctor\n"); }
  ~test(){ printf("dtor\n"); }
};
class test_content{
public:
  inline static test test_gobal;
};

int main() {}

编译代码以分别执行构造函数和析构函数一次(参见 GodBolt 上的这个)。所以你看到的可能是一个 MSVC 问题。


推荐阅读