问题
edit Tweaked example a little based on comments
A little code then the question (just to clarify, this is a C++ question):
#include <cstdio>
struct MYSTRUCT1 {
int asdf[4];
} MyStruct1;
struct MYSTRUCT2 {
int asdf[4];
MYSTRUCT2() : asdf() {}
} MyStruct2;
template <class T>
void test() {
T blah = {{1,-1,1,-1}};
for( int ii = 0; ii < 4; ii++ ) {
printf( "%d ", blah.asdf[ii] );
}
printf( "\n" );
}
int main() {
// Works fine; MyStruct1 doesn't define a constructor
test<MyStruct1>();
// Doesn't work; g++ complains I need to use `-std=c++0x`
// and/or define a constructor that allows the initialization
// taking place inside `test()`
test<MyStruct2>();
}
There's a few questions in here:
- What magic is going on that allows an instance of
MyStruct1
to be initialized in that manner - Is there a workaround for this in c++98?
For reference, I'm attempting to use constructors as a means to force stack allocated structs to be zero initialized, but I don't want to inhibit this style of initialization.
回答1:
What magic is going on that allows an instance of MyStruct1 to be initialized in that manner
Well, there's no "magic" per se. MyStruct1
is an aggregate type but, thanks to the ctor, MyStruct2
is not. You're attempting to perform aggregate initalisation, which may only be successful on an object of an aggregate type.
Is there a workaround for this in c++98?
Make your constructor do its job and take the arguments you need for initialisation.
Trying to use constructors to first zero-initialise everything seems like you're sort of half-thinking in C and half-thinking in C++ (correlated by your use of the antiquated typedef struct
idiom that has not been required in C++ for decades).
来源:https://stackoverflow.com/questions/15954208/when-initializing-a-struct-with-syntax-whats-happening-under-the-hood