Why there is no throw or sigsegv while accessing empty std::optional?

  • A+
Category:Languages

The example:

#include <optional> #include <iostream>  using namespace std;  int main() {     optional<int> t{}; // nullopt (empty) by default      cout << *t << endl;      return 0; } 

Actually this program prints some int (uninitialized value of type int). Also, libcxx uses assert-check for accessing non-engaged value.

Why the Standard does not require throwing or sigsegv here?

 


Why the Standard does not require throwing or sigsegv here?

Because requiring some particular behaviour implicitly imposes the requirement to add a branch to check whether that behaviour - be it throwing or something else - should occur.

By specifying that the behaviour is undefined, the standard allows the implementation to not check whether optional is empty upon every indirection. Branching the execution is potentially slower than not branching.

Rather than mandating safety, the committee let the standard library implementers to choose performance (and simplicity). The implementation that you tested seems to have chosen to not throw an exception or otherwise inform you of the mistake.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: