c++17 引入了内联(静态)变量。据说
"The compiler will guarantee that a variable has only one definition and it’s initialised only once through all compilation units."
我想知道 Visual C++ 是否保证内联静态变量在多个模块(dll 和 exe)中是唯一的。
//cat.h
class __declspec(dllexport) Cat
{
public:
inline static int var = 0;
};
如果 cat.h 包含在多个 dll 和一个 exe 中,Cat::var 在应用程序中是否唯一?
最佳答案
你的问题很“开放”,但是,如果你真正想要的只是一个实例,那么你应该定义一个宏 - 比如 DLLIMPEXP
- 有条件地定义为 __declspec (dllexport)
在一个模块中(实际定义或至少实例化类的地方),在另外两个模块中作为 __declspec(dllimport)
。然后有你的标题声明:
//cat.h
class DLLIMPEXP Cat
{
public:
inline static int var = 0;
};
注意 1:我认为类链接声明覆盖成员的。 注2:不一定是导出的DLL; EXE 也可以导出,DLL 也可以导入! 注3:正如其他人所说,C++17标准不(不能)适用于跨链接模块。
关于visual-c++ - 在 Visual C++ 中,内联静态变量是否跨模块唯一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57495423/