全局对象是如何在声明 const 之前构造的?

发布于 2024-11-02 18:00:51 字数 894 浏览 3 评论 0原文

我刚刚遇到一个奇怪的问题。在 WinMain.cpp 中,在包含用户创建的头文件之后,但在 WinMain 之前,我声明了 Brain 类的全局实例,如下所示:

(windows includes)
#include "BrainLib.h"
#include "Brain.h"

Brain brain;

(wndproc declaration)

WinMain() {
  (some code using Brain)
}

BrainLib.h 中,我声明了一些通用常量程序使用,例如 const unsigned Short SERVER_PORT = 12345; 和 const std::string SERVER_IP_STRING = "192.168.1.104"; 请注意,Brain.h 还包括 BrainLib.h

现在这里变得有趣了。 Brain 包含一个 Winsock 客户端包装类,该类仅连接到一台服务器。因此,Winsock 客户端有一个需要端口/IP 的构造函数,但没有默认构造函数。因此,它必须在 Brain 构造函数初始化列表中进行初始化,如下所示:

Brain::Brain() : winsockClient( SERVER_PORT, SERVER_IP_STRING )
{
}

但是,当调用 Brain 构造函数时,SERVER_IP_STRING 仍未初始化!我在 WinMain 中进行了检查,并在此时构建了它,但似乎 Brain 构造函数首先被调用,尽管它出现在第二个。怎么/为什么会这样?

另外,为了让这个更奇怪:我复制了源代码并在另一台机器上编译,并且它按预期工作。尽管我认为可能具有某种不同的构建设置,但每个版本上都运行相同版本的 MSVS 2008。

I just encountered a strange issue. In WinMain.cpp, AFTER I include a user-created header file, but BEFORE WinMain, I declare a global instance of my class Brain, like so:

(windows includes)
#include "BrainLib.h"
#include "Brain.h"

Brain brain;

(wndproc declaration)

WinMain() {
  (some code using Brain)
}

In BrainLib.h, I declare some constants for general program use, such as const unsigned short SERVER_PORT = 12345; and const std::string SERVER_IP_STRING = "192.168.1.104"; Note that Brain.h also includes BrainLib.h

Now here it gets interesting. Brain contains a Winsock client wrapper class that will only connect to one server. Thus, the Winsock client has a constructor requiring a port/ip and no default constructor. So, it must be initialized in the Brain constructor initialization list like so:

Brain::Brain() : winsockClient( SERVER_PORT, SERVER_IP_STRING )
{
}

However, SERVER_IP_STRING is still uninitialized when the Brain constructor is called! I put a check in WinMain, and it's constructed at that point, but it seems as though the Brain constructor is called first, even though it appears second. How/why can this be?

Also, just to make this stranger: I copied the source and compiled on a different machine, and it worked as expected. Same version of MSVS 2008 running on each, though I suppose possibly with some sort of different build settings.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北方的韩爷 2024-11-09 18:00:51

全局对象初始化的顺序未定义。

The order in which global objects are initialized is undefined.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文