Vector insert

Do I understand correctly that this innocent code is quite dangerous?

template<typename T> void insertLast(std::vector<T>& v) { if(v.empty()) return; v.insert(v.begin(), v.back()); } 

some clarification after reading some answers.

Well, I really do not ask how to insert an element into a vector, but I made a fictitious situation to question the principle. In other words, you think you need to make a copy (a temporary one is created here .. and a permanent link to a temporary one will be guaranteed to live):

 template<typename T> void insertLast(std::vector<T>& v) { if(v.empty()) return; v.insert(v.begin(), T(v.back())); } 
+4
source share
2 answers

It seems dangerous to me also, because vector.back () returns a link and

inserts at positions other than the end of the vector are performed by moving all the elements between the position and the end of the vector to their new positions, and then inserting a new element (s) (from here )

If I do not understand, the link passed to insert becomes "invalid" (if redistribution does not occur, it may contain not the last element but the previous one, otherwise it may still be right, but I think this is not guaranteed.

Perhaps, in some cases, some optimizers may hide the error (I think this never happens with objects, but it can happen with primitives), so you get the expected results, but in general I did not rely on this behavior.

+2
source

Assuming you turned to the two points mentioned in the comments to do this compilation, this would be done, but would leave the garbage value in front of the vector every time it starts because vector.back () returns a the link .

It looks like this is trying to do the following:

 template<typename T> void insertLast(std::vector<T>& v) { if(v.empty()) return; v.insert(v.begin(), v.end() - 1, v.end()); } 

This safely inserts the last element into the vector so that it is also the first element .... Assuming this is the desired behavior.

+1
source

Source: https://habr.com/ru/post/1436848/


All Articles