Reputation: 69968
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?]
Upvotes: 1
Views: 725
Reputation: 69968
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!
Upvotes: 5
Reputation: 234635
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.
Upvotes: 3