SamVanDonut SamVanDonut - 25 days ago 13
C++ Question

Why does erasing End-Iterator not give Segmentation Fault with shared_ptr?

The following Code runs without throwing a segemntation fault error. However, the call to

vec.erase
erases the last element, i.e. removes "pointer 1", reduces the size of vec by one and leaves "pointer 0" behind.

std::vector<std::shared_ptr<int>> vec;
vec.push_back(std::make_shared<int>(0));
vec.push_back(std::make_shared<int>(1));

vec.erase(vec.end());

std::cout << vec.size() << std::endl


The same code with just int throws a segmentation fault error, as excpected.

What is the reasons behind this?

PS: Tested with GCC 5.2.1

Answer

The same code with just int throws a segmentation fault error, as expected.

Your expectation is wrong. Undefined Behavior does not guarantee that your program would crash. It could be a surprise for you but behavior is undefined.

Comments