Default initialization of C++ Member arrays?

前端 未结 3 798
萌比男神i
萌比男神i 2020-12-15 18:21

This is a simple question, but I can\'t seem to find a definitive answer.

If we have the following class:

class Test
{
...
  char testArray[10];

...         


        
3条回答
  •  情歌与酒
    2020-12-15 19:05

    It depends on may factors that you forgot to mention.

    If your Test has no user-defined constructor or your user-defined constructor makes no efforts to initialize the array, and you declare the object of type Test as

    Test test; // no initializer supplied
    

    then it will behave in exactly the same way as you described above. For an automatic (local) object the contents of the array will remain unpredictable. For a static object the contents is guaranteed to be zero.

    If your class has a user-defined constructor, then it will all depend on what constructor does. Again, keep in mind that static objects are always zero-initialized before any constructor has a chance to do anything.

    If your class is an aggregate, then the content might depend on the aggregate initializer you supplied in the object declaration. For example

    Test test = {};
    

    will zero-initialize the array even for an automatic (local) object.

提交回复
热议问题