问题
I'm trying to initialize a LARGE_INTEGER
to 0 in a C++ library (C++03 to be exact). Previously, the initialization was:
static LARGE_INTEGER freq = { 0 };
Under MinGW it produced a warning:
missing initializer for member '_LARGE_INTEGER::::HighPart'
So I changed the initialization to the following in accordance with Can a union be initialized in the declaration?:
static LARGE_INTEGER freq = { .QuadPart = 0 };
I'm now testing under Visual Studio 2015, and its producing an error:
81 static LARGE_INTEGER freq = { .QuadPart = 0 };
82 if (freq.QuadPart == 0)
83 {
84 if (!QueryPerformanceFrequency(&freq))
85 throw Exception(Exception::OTHER_ERROR, "Timer: QueryPerformanceFrequency failed ..."));
86 }
hrtimer.cpp(81): error C2059: syntax error: '.'
hrtimer.cpp(81): error C2143: syntax error: missing ';' before '}'
hrtimer.cpp(82): error C2059: syntax error: 'if'
hrtimer.cpp(83): error C2143: syntax error: missing ';' before '{'
hrtimer.cpp(83): error C2447: '{': missing function header (old-style formal list?)
hrtimer.cpp(87): error C2059: syntax error: 'return'
How do I initialize a union to its largest member under the MSVC compiler?
Here is Microsoft's definiton of LARGE_INTEGER
:
#if defined(MIDL_PASS)
typedef struct _LARGE_INTEGER {
#else // MIDL_PASS
typedef union _LARGE_INTEGER {
struct {
DWORD LowPart;
LONG HighPart;
} DUMMYSTRUCTNAME;
struct {
DWORD LowPart;
LONG HighPart;
} u;
#endif //MIDL_PASS
LONGLONG QuadPart;
} LARGE_INTEGER;
回答1:
{ .QuadPart = 0 };
is illegal in C++. Designated initializers are C-only. You link to a c question.
In C++03 [dcl.init.aggr]/15: (your union is an aggregate):
When a union is initialized with a brace-enclosed initializer, the braces shall only contain an initializer for the first member of the union.
So, it is not possible to initialize "the largest member" unless that member is the first member.
The MinGW warning is bogus. g++ used to issue warnings for = { 0 };
, however that is a common idiom, so they fixed it to not do that any more. I guess you have a slightly old version.
In your code, = { 0 };
should initialize DUMMYSTRUCTNAME
to {0, 0}
. According to this, all members of your union are 64-bit so in this particular case, you did actually initialize the largest member.
来源:https://stackoverflow.com/questions/31638182/initialize-union-using-largest-member-under-msvc-compiler