1

想象一下我有这样的图书馆:

图书馆.h

   class DLLEXPORT LibraryClass
    {
    private:
      int _id;
      static int _last_id;
    public:
      LibraryClass();
      bool operator == (const LibraryClass t)
      {return _id == t._id;}
    };

图书馆.cpp

#include "Library.h"

int LibraryClass::_last_id = 0;

LibraryClass::LibraryClass()
_id(_last_id)
{
++_last_id;
}

它会正确工作吗?我在 Visual Studio 中收到 C4835 警告,但它似乎有效。有谁知道它将如何在其他编译器上工作(我对 linux gcc 和 mac gcc 感兴趣)?这种模式是否有另一种“有效”实现?

4

2 回答 2

1

您的语法很好,这不会导致您的代码出现任何问题;我认为您在编译时不会在 UNIX/MAC 系统上看到任何警告(除了您正在执行面向 Windows 的 DLL 导出这一事实)。我相信您只是看到托管 C++ 的后果。

来自 MSDN:

'variable' :在主机程序集中首次执行托管代码之前,不会运行导出数据的初始化程序

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.

于 2012-05-25T15:07:11.343 回答
1

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.

于 2012-05-25T15:07:15.963 回答