我正在将一个类移植到 C++,并且需要在创建我的类的第一个实例之前执行一些初始化代码;在 main()
获得控制之前执行代码适合我。如何用 C++ 实现?
最佳答案
初始答案
您可以在 namespace
范围内使用对象的构造函数。
namespace {
struct Init
{
Init()
{
// Initialization code here.
}
} init_;
} // namespace
请注意,这有一些限制,尤其是在 Windows 上。在 Windows 上,ctor 是在持有加载程序锁的情况下调用的,因此您不能执行任何需要加载 DLL 等的操作。这包括 WinSock 的初始化,因为它可以尝试加载外部 DLL。
更新
根据一些消息来源,您可以使用 QueueUserAPC
解决此限制。 .这种技术也有局限性,尽管有所不同。我已经使用过它,我的实验表明,只有当您将 Visual Studio 及其 C 库用作 DLL 时,它才有效,即 MSVCRT.DLL、MSVCR100.DLL 等(/MD
或 /MDd
开关)
更新2
这是一个link to similar issue (实际上是我的)有一点很重要:
After some testing it seems that the APC method works if I queue the APC from DllMain() but it does not work if I queue the APC from a ctor of a static global instance of a class.
关于c++ - 如何编写要在 main() 获得控制权之前执行的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18182949/