Devolus
Devolus

Reputation: 22104

Default value of std::vector for base types

I was trying find out how to inialize an std::vector<Object *> with a fixed size, because I don't need to change it anymore afterwards. So I'm using this code (the vector is empty before):

mControllerItem.resize(nLines,  nullptr);

According to the documentation the second element can be used to specify a default which will be copied into the new elements, but this is optional. If no second argument is given, then the default constructor is used.

In case of base types like pointer, int, etc.., what is used here? In the link it doesn't say anything about it. Will they be initialized to 0, do they stay undefined, or is there some other mechanism which determines what values they will get? In the example on the link the output is 0, so I assume that it is iniatliezed with that, but is this guaruanteed, or is this implementation (or un)defined?

Upvotes: 1

Views: 1581

Answers (3)

Jon
Jon

Reputation: 437534

The standard stipulates that resize will value-initialize any items that need to be inserted, so the behavior here is perfectly well defined.

In simple terms, value-initialization means:

  • for class types, the default constructor is called; if no constructor has been provided, then each member is value-initialized (recursively)
  • for scalars of any type T, they are given the value (T)0 (this guarantees that if T is a pointer the value used will be null portably)

Upvotes: 7

ArmanHunanyan
ArmanHunanyan

Reputation: 1015

Yes in case of pointers they will be initialized bu nulls. All base types have default constructors. The only difference is following

  1. int a; // default constructor will not be called so value is undefined
  2. class C {int a; C(): a()}; // default constructor will be called and value will be 0
  3. void f(int a = int()) // default constructor will be called and value will be 0

Upvotes: 1

ltjax
ltjax

Reputation: 16007

The behavior is defined slightly different between C++03 and C++11. In the former, a value-initialized object is created and the new elements in the vector are copy-constructed from that. In the new version, the new elements are value-initialized directly.

For built-in types like pointers, value-initialization equals zero-initialization, so your elements are, in-fact, guaranteed to be zero for both versions of the standard.

Note that your assumption that the default-constructor is used is actually not quite correct. It is, but only for custom types. It just happens that the syntax for value-initialization calls the default constructor for custom types, and zero-initializes for built-in types.

Upvotes: 3

Related Questions