When initializing a struct with ={} syntax, what's happening under the hood?

我的未来我决定 提交于 2019-12-12 03:55:41

问题


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:

  1. What magic is going on that allows an instance of MyStruct1 to be initialized in that manner
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!