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?]
For C++23, constructing std::string or std::string_view from nullptr/NULL/0 is forbidden
A Proposal to Prohibit std::basic_string and std::basic_string_view construction from nullptr.
Though one may not use string s = nullptr in practice, it may get triggered sometimes unintentionally in a generic code. e.g.
template<typename T> struct X { ... T t = 0; ... }; X<int> xi; // ok X<float> xf; // ok X<string> xs; // c++20 = runtime assert? --- c++23 = compiler error! 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.
const char*.
std::logic_error" - This attempted initialization never throws, it always results in UB.std::string s = nullptr;is not allowed. C++ often does not prevent you from doing something that is not allowed at compile time, nor does it (typically) check for the not allowed thing at run time. C++ is not a nanny language, it presumes the source code is valid.string s = nullptr;See this answer. It's always good to have features which fix trivial errors at compile time to avoid waste of efforts.