Behaviour of Initializer List for Array of Struct

I have scanned through a few C++ books but none of them describe this in detail:

With VC++ 2010, I created a struct with constructors deliberately added for testing:

struct BufferElement {
    size_t currentAllocationSize;
    BufferElement() {
        currentAllocationSize=50;
    }
    BufferElement(size_t size) {
        if (size==0)
            currentAllocationSize=20;
        else 
            currentAllocationSize=1;
    }
};

And I have an array of this struct type:

int _tmain(int argc, _TCHAR* argv[])
{
    BufferElement buffers[10]={0};
    buffers[6]=0;
    for (int i=0; i<sizeof buffers/ sizeof buffers[0]; i++) {
        printf("%dn", buffers[i].currentAllocationSize);
    }

    return 0;
}

Result:

20
50
50
50
50
50
20
50
50
50

I expect my array initializer list {0} should initialize all of the elements to 0. Since this is an array of struct, 0 should mean calling the constructor with 0. But the test shows that apart from the first element, all of them are invoked with the default constructor. Is this a standard behaviour? How should I interpret the array initializer {0} when the array type is a struct? How do I ensure my single arg constructor is called instead without having to use {0,0,0,0,0,0,0,0,0,0}? Since my array size may change.


You are only specifying a value for the first element, so that one element will be initialized with BufferElement(your-value) . The rest of the elements have no value specified, so they will use the default constructor. That's what happens for class and struct types.

In arrays of built in types, like int , the remaining values would instead be value-initialized, which makes them zero. Not so for class objects.


But the test shows that apart from the first element, all of them are invoked with the default constructor.

If you initialize only some elements of an array, any remaining elements will be initialized with default constructor.


Initializing all the elements of an array by giving just one value ( {0} ) is not required by the standard. Since this is an array of struct s, their default constructors are called to initialize them.

If you want to initialize them all with a specific value, you should list all the elements, like this: {0, 0, 0, 0, ..., 0} .

You can use an std::vector and initialize all like this:

std::vector<BufferElement> vec(10, BufferElement(0));
链接地址: http://www.djcxy.com/p/67784.html

上一篇: 在C ++ 11和std :: vector构造函数中初始化对象

下一篇: 结构数组的初始化列表行为