3

If I understand the documentation correctly, std::string::replace may replace some part of a string even with a longer string:

std::string s("hello");
s.replace(s.begin() + 1, s.end() - 1, ".....");
std::cout << s;  // prints "h.....o"

This might require reallocation if the capacity is not high enough for a new string. However, the exception specification for replace in the C++11 Standard does mention only out_of_range and length_error exceptions.

In the current draft, there are additionally specified exceptions thrown by the allocator's allocate member function [string.replace.8.3]:

Throws: ...

any exceptions thrown by allocator_­traits<Allocator>​::​allocate.

I wonder why these exceptions are not specified in C++11? May library functions throw additional exceptions not specified in the Throws: clause?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Daniel Langr
  • 22,196
  • 3
  • 50
  • 93

1 Answers1

2

It was a bug; the committee fixed it only recently. Some such fixes are explicitly called out as being retroactive (i.e., implementations are expected to behave the new way even in old language modes). This one wasn’t, perhaps because it’s, er, highly unlikely that any implementation ever behaved any other way.

In short, don’t read too much into it.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
  • Thanks. My question was motivated by a different one where OP asked whether `replace` may invalidate a pointer/iterator to a character being in front of the replaced part, which was replaced by a shorter string. If `replace` didn't throw allocator's execptinos, then this would actually imply that no reallocation may happen and therefore the pointer wouldn't be invalidated. Which might easily translate a bug in the Standard into a bug in the code. – Daniel Langr Sep 02 '19 at 07:00
  • @DanielLangr I think that is part of [LWG issue 2318](https://cplusplus.github.io/LWG/issue2318). It seems to me that before adoption of p1148r0, any exception-less call to `replace` would invalid all pointers. Can you link the question you are referring to? – walnut Sep 02 '19 at 08:28
  • @uneven_mark [Does string::replace invallidate iterators and references?](https://stackoverflow.com/q/57748791/580083). – Daniel Langr Sep 02 '19 at 08:46
  • The final part of the question still remains unanswered though: "May library functions throw additional exceptions not specified in the Throws: clause?" – Aykhan Hagverdili Sep 02 '19 at 18:21
  • 1
    @Ayxan: No, they [can’t](http://eel.is/c++draft/res.on.exception.handling#1); the implementation-defined exceptions freedom is only in the *absence* of such a paragraph. – Davis Herring Sep 02 '19 at 18:41