Lavanya Narayanaswamy
Lavanya Narayanaswamy

Reputation: 31

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

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?

Upvotes: 3

Views: 97

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473272

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.

Upvotes: 7

Related Questions