【发布时间】:2018-03-30 05:43:28
【问题描述】:
自 C++17 以来,我一直在尝试更简单的方法来获取类静态变量。我正在编写一个仅限标题的库。显然inline 对变量的新含义很适合这个。
class thingy {
static inline reporter rep;
};
但我遇到了运行时错误。
我使用的是 Visual Studio 15.6.4
为了测试,如下:
-
thingy有一个静态成员变量 - 成员告诉你它何时被构造/销毁以及在什么地址
- 应该只构造和销毁一次
- #include 包含在两个 .cpp 文件中
foo.h
#pragma once
#include <iostream>
using namespace std;
struct reporter {
reporter() {
cout << "reporter() - " << this << endl;
}
~reporter() {
cout << "~reporter() - " << this << endl;
}
};
class thingy {
static inline reporter rep;
};
main.cpp
#include "foo.h"
int main() {}
foo.cpp
#include "foo.h"
最令人失望的是,它会打印:
reporter() - 00007FF670E47C80
reporter() - 00007FF670E47C80
~reporter() - 00007FF670E47C80
~reporter() - 00007FF670E47C80
如您所见,它在同一个位置被构造了两次并被破坏了两次 - 不好。
我是否误解了变量上的inline 的用途?
还有其他方法可以仅在标题中获取类静态信息吗?这在 C++17 中是否发生了变化?
【问题讨论】:
标签: c++ visual-c++ c++17 static-variables