C++ - value of uninitialized vector

后端 未结 5 1520
情歌与酒
情歌与酒 2020-12-03 09:28

I understand from the answer to this question that values of global/static uninitialized int will be 0. The answer to this one says that for vectors, the default construc

5条回答
  •  情话喂你
    2020-12-03 10:06

    The constructor you are using actually takes two arguments, the second of which is optional. Its declaration looks like this:

    explicit vector(size_type n, const T& value = T())
    

    The first argument is the number of elements to create in the vector initially; the second argument is the value to copy into each of those elements.

    For any object type T, T() is called "value initialization." For numeric types, it gives you 0. For a class type with a default constructor, it gives you an object that has been default constructed using that constructor.

    For more details on the "magic parentheses," I'd recommend reading Michael Burr's excellent answer to the question "Do the parentheses after the type name make a difference with new?" It discusses value initialization when used with new specifically, but for the most part is applicable to value initialization wherever else it can be used.

提交回复
热议问题