-6

The following crashes:

  std::map<std::string, int> m1{ {"0", 0}, { "1", 1 }};
  // auto melem = m1["0"]; // OK
  auto melem = m1[0];

Why is that?

Korchkidu
  • 4,908
  • 8
  • 49
  • 69

1 Answers1

7

Unfortunately (thanks C!) it is "possible" to construct a std::string from the integer 0, because it counts as a null pointer literal.

However, it's not really possible:

Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if [s, s + Traits::length(s)) is not a valid range (for example, if s is a null pointer).

You got a crash because you tried to create a std::string from a null pointer.

At least with GCC the result of this contract violation is an [unhandled] exception with a descriptive name:

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid

Unfortunately, though, you can't rely on this, and you don't get any warnings during build.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055