-2

As per default (http://www.cplusplus.com/reference/vector/vector/resize/) resize() on a vector will call the default constructor.

Suppose I call push_back() on a vector and it resizes due to that - will it then also initialize the newly allocated space? If so - why? Leaving things uninitialized first could be efficient if the client calls for example push_back() because then one could simply copy the object as a whole instead of having to use the copy constructor as it would be the case if the memory location would already have been initialized.

Rupesh Yadav.
  • 894
  • 2
  • 10
  • 24
ben
  • 5,671
  • 4
  • 27
  • 55
  • 4
    Suppose calling `push_back` doesn't call `resize()`... – juanchopanza Nov 18 '14 at 06:55
  • Seriously guys, calm down with the downvotes. – zneak Nov 18 '14 at 07:04
  • "If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are **value-initialized**." Looking at your "reference" it actually says that `resize()` does value initialize it. It's nowhere said that vector uses it after `push_back`s though. – AliciaBytes Nov 18 '14 at 07:07
  • @OP You're confusing `std::vector::resize()` with `std::vector::reserve()` actually. – πάντα ῥεῖ Nov 18 '14 at 07:15
  • Yes I mixed something up here. – ben Nov 18 '14 at 14:28

1 Answers1

2

std::vector won't call the resize() function when it runs out of space with a push_back() call. Also there are two related functions in the vector.

reserve() which reserves space for more elements but doesn't call any constructor on them. Also it doesn't change the size of the vector.

resize() which gives the vector the new size. When you got an vector with 5 elements and call vector.resize(10) calling vector.size() afterwards would also return 10 since it fills up with value-initialized elements.

When the vector runs out of space due to calling push_back() on it it'll most likely call reserve() or an internal version of it.

Employee
  • 3,109
  • 5
  • 31
  • 50
AliciaBytes
  • 7,300
  • 6
  • 36
  • 47