Search code examples
c++cinitializationaggregate-initializationdesignated-initializer

What's this type of initialization called?


I saw code in a Vulkan tutorial that goes:

VkImageMemoryBarrier imageMemoryBarrier = {
 
   .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT,
   .dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
   .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
   .newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
            /* .image and .subresourceRange should identify image subresource accessed */ 
};

If I just had the enums listed without the member '.member_name =' it would be aggregate-initialization, right? But what is this called? This class has other members before .srcAccressMask, I assume all other members that aren't mentioned are zero-initialized? But it's a bit hard to look this up if I don't know what it's called. Also, I remember something like this being a new C feature, but it compiles in C++ for me in Visual Studio. It's a C++ feature, right?


Solution

  • This is still aggregate initialization, with the syntax of designated initializers supported since C++20.

    T object = { .designator = arg1 , .designator { arg2 } ... }; (3) (since C++20)
    T object { .designator = arg1 , .designator { arg2 } ... };   (4) (since C++20)
    

    And about members not mentioned in initializer:

    For a non-union aggregate, elements for which a designated initializer is not provided are initialized the same as described above for when the number of initializer clauses is less than the number of members (default member initializers where provided, empty list-initialization otherwise):

    BTW: Rules in C++ are not the same as C.

    Note: out-of-order designated initialization, nested designated initialization, mixing of designated initializers and regular initializers, and designated initialization of arrays are all supported in the C programming language, but are not allowed in C++.