visual-c++ - 在 Visual C++ 中,内联静态变量是否跨模块唯一?

标签 visual-c++ dll c++17

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/

相关文章:

c++ - 结构化绑定(bind) : loop over deque of tuple

windows - 对于 64 位 Windows 上的 32 位应用程序,64 位操作是原子的吗

c++ - 数组声明错误 : Expression must have a constant value

c++ - 模板类的 VS 编译器错误

插件的 C++ 多态基类层次结构设计

c++ - std::pair<auto, auto> 返回类型

c++ - 如何解决std::allocator的不推荐使用?

c++ - 从 UWP vc++ 中生成的字节数组生成图像

c++ - 如何从 Visual Basic 调用 C++ 构造函数

c# - 类库在使用时丢失引用(dll)