Reputation: 153
Imagine i have such library:
Library.h
class DLLEXPORT LibraryClass
{
private:
int _id;
static int _last_id;
public:
LibraryClass();
bool operator == (const LibraryClass t)
{return _id == t._id;}
};
Library.cpp
#include "Library.h"
int LibraryClass::_last_id = 0;
LibraryClass::LibraryClass()
_id(_last_id)
{
++_last_id;
}
Will it work correct? I'm getting C4835 warning in Visual Studio, but seems it works. Does anybody know how it will work on other compilers (i'm interested in linux gcc and mac gcc)? Is there another "valid" implementation for such pattern?
Upvotes: 1
Views: 2204
Reputation: 39294
Your syntax is fine and this shouldn't cause any issues in your code; I don't think you'd see any warnings on a UNIX/MAC system while compiling this (except for the fact that you're doing a DLL export which is windows oriented). I belive you're just seeing fallout of managed C++.
From MSDN:
'variable' : the initializer for exported data will not be run until managed code is first executed in the host assembly
When accessing data between managed components, it is recommended that you not use native C++ import and export mechanisms. Instead, declare your data members inside a managed type and reference the metadata with #using in the client. For more information, see #using Directive (C/C++).
Your static data member will be in the initialized test segment of your program when compiled on unix. It is guaranteed to be initialized to the value you provided prior to execution, so it will start at 0, and it will be completely usable in your constructor by the time it is invoked.
Upvotes: 1
Reputation: 299810
From the documentation it seems that the issue only arise if you attempt to use the value in the initialization phase (prior to main
). Apparently an issue related to managed mode.
The C++ Standard is very clear regarding this: _last_id
it will be first statically initialized to 0
prior to any dynamic initialization, meaning that any conformant compiler will produce code that works as you would expect.
Therefore, it will work with gcc and clang (whatever the OS).
For Visual Studio, I am not sure (not savvy enough) if the issue will appear systematically or only if you require the managed mode with some flags.
Upvotes: 1