What is the element value in an uninitialized vector?

前端 未结 3 1090
孤独总比滥情好
孤独总比滥情好 2021-01-28 08:31

If I create a vector like vector v(10); what is the default value of each element?


Also, what if it is a vector v(

相关标签:
3条回答
  • 2021-01-28 08:52
    vector<myClass> v;
    

    its a empty vector with size and capacity as 0.

    0 讨论(0)
  • 2021-01-28 08:54

    The answer to your second question is similar; vector<myUnion> v(10) will create an array of 10 myUnions initialized with their default constructor. However note that: 1) Unions can't have members with constructors, copy constructors or destructors, as the compiler won't know which member to construct, copy or destroy, and 2) As with classes and structs, members with built-in type such as int will be initialized as per default, which is to say not at all; their values will be undefined.

    0 讨论(0)
  • 2021-01-28 08:55

    The constructor of std::vector<> that you are using when you declare your vector as

    vector<myClass> v(10);
    

    actually has more than one parameter. It has three parameters: initial size (that you specified as 10), the initial value for new elements and the allocator value.

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

    The second and the third parameters have default arguments, which is why you were are able to omit them in your declaration.

    The default argument value for the new element is the default-contructed one, which in your case is MyClass(). This value will be copied to all 10 new elements by means of their copy-constructors.

    What exactly MyClass() means depends on your class. Only you know that.

    P.S. Standard library implementations are allowed to use function overloading instead of default arguments when implementing the above interface. If some implementation decides to use function overloading, it might declare a constructor with just a single parameter (size) in std::vector. This does not affect the end result though: all vector elements should begin their lives as if they were value-initialized.

    0 讨论(0)
提交回复
热议问题