Suppose I have a std::vector<foo>
now I understand that insertion at the end of a vector is amortized constant. Which means it could either be O(1) or O(n) (since it acquire a new memory block , copies the old content into the new memory block). My question is when the items are copied to a newer memory block (supposedly larger) is the copy constructor of the object called again ? (The first time the copy constructor gets called is with a push_back) , in my case will the copy constructor of foo be called again upon resize of a vector ? I know with a std::deque the copy constructor wont be called since it stores the addresses of the objects on a heap and maintains them in a vector type data structure. will the behavior be same in C++98 and C++11
Asked
Active
Viewed 2,408 times
5

MistyD
- 16,373
- 40
- 138
- 240
-
1The elements will be copied or move copied. This can be easily checked with a verbose type. BTW your interpretation of how `deque` works is off. – juanchopanza Nov 25 '14 at 21:24
-
could you also expand on the deque part with an overview ? I am pretty sure copy constructors wont be called again in case of a deque. http://stackoverflow.com/questions/8627373/what-data-structure-exactly-are-deques-in-c – MistyD Nov 25 '14 at 21:25
-
See http://stackoverflow.com/questions/6292332/what-really-is-a-deque-in-stl – juanchopanza Nov 25 '14 at 21:27
1 Answers
6
For the most part, yes, copy constructors will be called.
As of C++11 std::vector will try to move objects when reallocating. If your object has a move constructor that will be called instead of the copy constructor.
Thanks to Piotr I now know that std::vector
uses std::move_if_noexcept
to determine if the move constructor can be called without throwing an exception. See http://en.cppreference.com/w/cpp/utility/move_if_noexcept for more information.

Jay Miller
- 2,184
- 12
- 11
-
1*"If your object has a move constructor that will be called instead of the copy constructor."*, consider mentioning `std::move_if_noexcept` – Piotr Skotnicki Nov 25 '14 at 21:27
-
so incase of C++98 is the destructor of the old object called after its copied to new location ? and also does the pointer of the old location become invalid ? – MistyD Nov 25 '14 at 21:30
-
Yes, old objects are destroyed after they are copied to the new buffer. – Jay Miller Nov 25 '14 at 21:38