问题
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