Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about pop_back(), C++

Tags:

c++

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

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

Maybe it is right but it surprises me that it prints out 1. So I am confused. Is pop_back() only able to remove the element has index > 0 ?

Thanks in advance!

like image 226
Brian Avatar asked Nov 27 '22 14:11

Brian


2 Answers

You are invoking undefined behaviour by calling front on an empty vector. That's like indexing out of the bounds of an array. Anything could happen, including returning 1.

like image 142
Seth Carnegie Avatar answered Dec 07 '22 01:12

Seth Carnegie


pop_back here leaves the vector empty. Accessing an empty vector's front() is undefined behavior. This means that anything can happen - there's no predicting what. It could crash, it could return 1, it could return 42, it could print "Hello, world!", it could erase your hard drive, or it could summon demons through your nasal passages. Any of these are acceptable actions, as far as C++ is concerned - here it just happened to end up returning 1. Don't rely on it.

like image 42
bdonlan Avatar answered Dec 07 '22 00:12

bdonlan