'std::optional compile passes, but run fails [duplicate]

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source