logoalt Hacker News

on_the_trainyesterday at 6:46 PM4 repliesview on HN

std::optional is unsafe in idiomatic use cases? I'd like to challenge that.

Seems like the daily anti c++ post


Replies

steveklabnikyesterday at 6:59 PM

Two of the authors are libc++ maintainers and members of the committee, it would be pretty odd if they were anti C++.

maccardyesterday at 7:08 PM

I’m very much pro c++, but anti c++’s direction.

> optional is unsafe in idiomatic use cases? I’d like to challenge that.

    std::optional<int> x(std::nullopt);
    int val = *x;

Optional is by default unsafe - the above code is UB.
show 2 replies
boulosyesterday at 7:09 PM

They linked directly to https://alexgaynor.net/2019/apr/21/modern-c++-wont-save-us/ which did exactly what I'd guessed as its example:

> The following code for example, simply returns an uninitialized value:

  #include <optional>

  int f() {
    std::optional<int> x(std::nullopt);
    return *x;
  }
show 1 reply
canypyesterday at 7:36 PM

It is discussed in the linked post: https://alexgaynor.net/2019/apr/21/modern-c++-wont-save-us/

tl;dr: use-after-move, or dereferencing null.