When do C++ POD types get zero-initialized?

前端 未结 5 1868
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 03:23

Coming from a C background, I\'ve always assumed the POD types (eg ints) were never automatically zero-initialized in C++, but it seems this was plain wrong!

My unde

5条回答
  •  长情又很酷
    2020-12-10 03:37

    Assuming you haven't modified a before calling test(), a has a value of zero, because objects with static storage duration are zero-initialized when the program starts.

    d[0] has a value of zero, because the constructor invoked by std::vector d(1) has a second parameter that takes a default argument; that second argument is copied into all of the elements of the vector being constructed. The default argument is T(), so your code is equivalent to:

    std::vector d(1, int());
    

    You are correct that b has an indeterminate value.

    f.a and *c both have indeterminate values as well. To value initialize them (which for POD types is the same as zero initialization), you can use:

    Foo f = Foo();      // You could also use Foo f((Foo()))
    int* c = new int(); // Note the parentheses
    

提交回复
热议问题