Are inline static variables unique across modules in visual c++?

孤街醉人 提交于 2021-01-27 12:23:25

问题


c++17 introduce inline (static) variables. It is said that

"The compiler will guarantee that a variable has only one definition and it’s initialised only once through all compilation units."

I am wondering if visual c++ guarantee inline static variable will be unique across multiple modules (dlls and exe).

//cat.h
class __declspec(dllexport) Cat
{
public:
    inline static int var = 0;
};

If cat.h is included in multiple dlls and one exe, is Cat::var unique in the application ?


回答1:


Your question is quite 'open-ended' but, if what you actually want is only one instance, then you should define a macro - say DLLIMPEXP - that is conditionally defined as __declspec(dllexport) in one module (where the class is actually defined, or at least instantiated) and as __declspec(dllimport) in the other two. Then have your header declaration:

//cat.h
class DLLIMPEXP Cat
{
public:
    inline static int var = 0;
};

Note1: I think the class linkage declaration overrides the member's. Note2: It doesn't have to be a DLL that exports; EXEs can export too, and DLLs can import! Note3: As others have said, the C++17 standard does not (cannot) apply across link modules.



来源:https://stackoverflow.com/questions/57495423/are-inline-static-variables-unique-across-modules-in-visual-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!