c++ - 为什么具有静态存储持续时间的同一个内联变量在包含在由 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 错误,不管这个引用是什么?
解决方案
好吧,首先,我不清楚你甚至可以 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 问题。
推荐阅读
- node.js - Node/Express/MongoDB 应用程序:使用 Multer 和 Cloudinary 上传多个图像
- javascript - Chrome Web 扩展,使用按钮在新标签页中打开网页
- python - 当第二个元素是向量/数组时,Numpy 矩阵乘法失败(“形状未对齐”)
- webpack - 错误:找不到模块“stylelint”Webpack
- php - Laravel,努力使用查询生成器重现查询
- mysql - 插入值 + 最大 ID
- python - 找不到 Behave 的配置文件
- java - SQL IN 或 NOT IN 取决于布尔参数
- javascript - unmute.roles.has(muterole) 失败
- json - 当json属性包含空格时如何将json字符串转换为对象