开发者

Can POD-structs be initialized using named attributes in a portable way in C++?

开发者 https://www.devze.com 2023-02-26 16:13 出处:网络
I am tryi开发者_运维技巧ng to initialize a struct using named attributes in a way that is compatible both with GCC 4.3.4 and Clang 2.9.

I am tryi开发者_运维技巧ng to initialize a struct using named attributes in a way that is compatible both with GCC 4.3.4 and Clang 2.9.

struct A {
  unsigned int x;
};

// GCC: error: expected primary-expression before '.' token
A a = {
  .x = 0xdeadbeef;
};

// Clang: error: use of GNU old-style field designator extension [-Werror,-Wgnu-designator]
A a = {
  x : 0xdeadbeef;
};

I cannot add -Wno-gnu-designator to CXXFLAGS because then GCC will refuse to build since it does not know that flag. I cannot use an initialization list without naming attributes because if the API changes we are going to have serious issues.

The solution I need has to conform to the C++ standard while retaining the fact that if new attributes appear in the struct they should be uninitialized (or preferably NULL). The structs are third party and I cannot alter them in any way.


No, you cannot name the values, just give them in order.

A a = { 42 };

If new fields are added at the end of the struct, they will be zeroed.


You could do something like this:

#if THIS_IS_GCC
  #define INIT_ATTR(x,y) x : y;
#elif THIS_IS_LLVM
  #define INIT_ATTR(x,y) .x=y;
#else
  #error Can't do it :/
#endif

A a = {
  INIT_ATTR(x,0xdeadbeef)
};

However this is really not standard C++.

Is anything wrong with :

A a;
a.x = y;
0

精彩评论

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