Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the copy-ctor preferred over move-ctor when std::vector relocates storage? [duplicate]

When std::vector reallocate its memory array, what kind of copy / move constructor is used to copy / move elements to new houses?

like image 512
duong_dajgja Avatar asked Jul 26 '17 01:07

duong_dajgja


1 Answers

If the move-constructor exists and is noexcept then it is used. Otherwise the copy-constructor is used.

Using a move-constructor that might throw is undesirable as it might happen that some objects are moved to the new storage and then an exception prevents the rest of the objects being moved.

The cppreference.com site does say that if the object is non-copyable , but has a non-noexcept move constructor, then it will use that move-constructor, with "unspecified behaviour" if an exception is thrown. I guess that means elements may be lost from the vector.

like image 192
M.M Avatar answered Oct 17 '22 23:10

M.M