开发者

How is a global object constructed before a const it was declared after?

开发者 https://www.devze.com 2023-02-27 02:26 出处:网络
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:

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.


The order in which global objects are initialized is undefined.

0

精彩评论

暂无评论...
验证码 换一张
取 消