1
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?]

7
  • "[...] throws std::logic_error" - This attempted initialization never throws, it always results in UB. Commented Jun 5, 2020 at 11:25
  • 4
    @dfri "never does X" and "always UB" are mutually exclusive. UB can have any behaviour and thus there is nothing that could never happen. Commented Jun 5, 2020 at 11:32
  • @eerorika Yes you are right, of course (here be demons flying out of our noses); but I hope my main point to emphasize on the fact that this is UB rather than this seemingly throwing in a well-defined manner was not lost to anyone. Commented Jun 5, 2020 at 11:34
  • The question is a bit misleading. The 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. Commented Jun 5, 2020 at 12:12
  • @Eljay, you may want to revise your opinion. With C++23, it's proposed to prevent 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. Commented Jul 6, 2022 at 9:33

2 Answers 2

5

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! 
Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

I think they have a good reason: such a constructor would only catch sillynesses as written in the OP, but it wouldn't catch assignments of null pointer values of type const char*.
As of C++23, some of this answer is no longer accurate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.