Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between std::string::resize and std::string::erase when shortening string

Tags:

c++

c++11

When shortening a std::string there are basically two possibilities: string.resize(length) or string.erase(length).

Given that we know a string will become smaller, what are the differences between the two?

like image 518
zennehoy Avatar asked Nov 10 '22 01:11

zennehoy


1 Answers

  1. resize must check if length > current or length < current - it's behavior depends on result of сomparison. erase always reduce length of string
  2. There is difference in exception safety:
    • resize: Strong guarantee: if an exception is thrown, there are no changes in the string. ( from here )
    • erase: C++98 - equal to resize; C++14 - there is no-throw version of function ( from here )
like image 93
Roman Zaitsev Avatar answered Nov 15 '22 07:11

Roman Zaitsev