0

I've been trying to introduce std::optional into my projects lately, and it's great! But now I'm a bit confused, look at the following code:

#include <iostream>
#include <optional>
#include <string>

using namespace std;

int main()
{
    std::optional<string> s = nullptr;

    return 0;
}

This code build normally without any warnings! This is bad, because if I accidentally assign nullptr to std::optional in my project, it will cause a panic, but I can't find it at compile time! There may be other ways to catch this error at compile time, but I don't know of them right now. Does anyone have any good ideas?

xm lian
  • 73
  • 13
  • 5
    it's not relate to optional, you can also write `string s = nullptr;` – apple apple May 01 '22 at 16:08
  • 1
    It would be nice if `basic_string` had a deleted overload for `std::nullptr_t` to make it at least a little harder to try to construct one with an invalid `const char*`. – Nathan Pierson May 01 '22 at 16:11
  • 1
    maybe better dupe https://stackoverflow.com/questions/62214089/why-is-assignment-of-0-or-nullptr-to-stdstring-allowed-even-when-it-results-i – apple apple May 01 '22 at 16:11
  • @NathanPierson I believe most of the time it's when construct from a `char*`, that'd not help much. – apple apple May 01 '22 at 16:12
  • Also see https://softwareengineering.stackexchange.com/questions/309888/compile-time-checking-for-null-initialized-stdstring – cigien May 01 '22 at 16:13
  • 1
    Since C++23 adopted [p2166r1](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2166r1.html), `std::string` construction from `nullptr` is now prohibited, that is, your code will no longer be well-formed in C++23. Mind if I reopen the question? – 康桓瑋 May 01 '22 at 16:13
  • @康桓瑋 Oh, nice :) If that proposal has been merged into the WD, you should add an answer on the first linked target. Regardless, there's no reason to reopen this question. The change to the specs can be added as an answer on the target. – cigien May 01 '22 at 16:14
  • @appleapple Got it, thanks! But it's shocking that `std::string s = nullptr` can compile through without any warning. – xm lian May 01 '22 at 16:34
  • Personally I think it just too rare to be considered, most of the time, it comes from `char*`, not `nullptr_t`. (I believe `string s=0;` doesn't prevent by that proposal either) – apple apple May 01 '22 at 18:01

0 Answers0