简体   繁体   中英

What is the defined behavior of std::string::erase() with a pos of string::npos?

What does the C++11 standard specify for the behavior of the string& erase (size_t pos = 0, size_t len = npos); member function when the pos argument is passed as string::npos ? I would think it should erase nothing, but perhaps it throws an out_of_range exception instead? What is the defined behavior for the standard?

It throws std::out_of_range , as specifically stated in the standard:

21.4.6.5 basic_string::erase [ string::erase ]

basic_string& erase(size_type pos = 0, size_type n = npos);

Requires : pos <= size()

Throws : out_of_range if pos > size() .

Effects : Determines the effective length xlen of the string to be removed as the
smaller of n and size() - pos . The function then replaces the string controlled by *this with a string of length size() - xlen whose first pos elements are a copy of the initial elements of the original string controlled by *this , and whose remaining elements are a copy of the elements of the original string controlled by *this beginning at position pos + xlen .

Returns : *this .

It throws std::out_of_range . See http://en.cppreference.com/w/cpp/string/basic_string/erase .

The general principle is that values of pos between 0 and size() (ie one past the end) are fine, but anything beyond that indicates caller error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM