Confusingly about pop_back (), C ++

I am trying to understand the behavior of vector::pop_back() . Therefore, I have the following code snippet:

 vector<int> test; test.push_back(1); test.pop_back(); cout << test.front() << endl; 

This may be right, but it surprises me that it prints 1. So I'm confused. Does pop_back() only have a way to remove an index > 0 element?

Thanks in advance!

+4
source share
2 answers

You invoke undefined behavior by calling front on an empty vector. This is similar to indexing the boundaries of an array. Anything can happen, including refund 1 .

+18
source

pop_back here leaves the vector empty. Access to empty vectors front() is undefined behavior. This means that something can happen - there is no prediction. It may fall, it may return 1, it may return 42, it may print β€œHello world!” It may erase your hard drive, or it may cause demons through your nasal passages . Any of these are acceptable actions as far as C ++ is concerned - return 1 just ended here. Do not rely on this.

+10
source

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


All Articles