Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does std::string::erase remove characters from a string?

Tags:

c++

string

c++11

Consider the following code for example.

string str = "Alice ate apples"; 
str.erase(0, 2)

Does erase function actually allocate new memory and copy the "ice ate apples" or does erase function do an in-place copy?

like image 584
Lavanya Narayanaswamy Avatar asked Jan 26 '26 04:01

Lavanya Narayanaswamy


1 Answers

It is illegal for a basic_string implementation to have the iterator forms of erase throw exceptions. And even the index form of erase only throws when you provide an out-of-range index.

That's important because allocating memory is a potentially throwing operation. So if erase cannot throw, then it cannot allocate either. So it doesn't.

Therefore, the erasure must happen in-place.

like image 53
Nicol Bolas Avatar answered Jan 28 '26 16:01

Nicol Bolas