Inside a function, I have a static variable which is a struct, and only one of its fields are initialized:
void func() {
static constexpr xcb_change_window_attributes_value_list_t root_mask {
.event_mask = XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_LEAVE_WINDOW |
XCB_EVENT_MASK_PROPERTY_CHANGE |
XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY
};
// do something else
}
I would like to know if the struct is guaranteed to be zero initialized before the one field inside it is set, or would the only initialization happening be just on the single field? The struct has about 15 other members which I explicitly do not want to have any other values but their default.
A better way I've discovered is to use a constexpr
lambda (since C++17) function to create the variable:
void func() {
static constexpr auto root_mask = []() constexpr {
xcb_change_window_attributes_value_list_t mask{}; // initialize here
mask.event_mask =
XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_LEAVE_WINDOW |
XCB_EVENT_MASK_PROPERTY_CHANGE | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY;
return mask;
}();
// do something else
}
This way, the struct is fully initialized to zero, and compiler doesn't complain.