MistyD
MistyD

Reputation: 17223

Will copy constructor of an object be called upon resize of a vector

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

Upvotes: 5

Views: 2930

Answers (1)

Jay Miller
Jay Miller

Reputation: 2234

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.

Upvotes: 6

Related Questions