c++c++14language-lawyerstdstringnullptr

Why is assignment of 0 or nullptr to std::string allowed, even when it results in a straight forward runtime exception?


std::string s = 0;  // = nullptr ---> throws `std::logic_error`

Above statement results in segmentation fault. Why is it allowed?
[At least the constructor overload of nullptr should have been =delete, isn't it?]


Solution

  • In that case, the constructor to a const char* is called due to the way overload resolution works.

    And if that pointer is nullptr then the standard library attempts to dereference a null pointer value with undefined results.

    std::string is already hideously bloated. My guess is that nobody has managed to convince the C++ standards committee of the merits of having a std::string(std::nullptr_t) constructor.