https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109281
Bug ID: 109281 Summary: use std::optional results in suboptimal code Product: gcc Version: 12.2.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: vincenzo.innocente at cern dot ch Target Milestone: --- In the following (almost real) code gcc emits suboptimal code if std::optional is used w/r/t home made one and clang see https://godbolt.org/z/Pba51Ye7Y ----- code #include <optional> // #define USE_OPTIONAL #ifdef USE_OPTIONAL struct SubRingCrossings { SubRingCrossings(int ci, int ni, float nd) : closestIndex(ci), nextIndex(ni), nextDistance(nd) {} int closestIndex; int nextIndex; float nextDistance; }; #else struct SubRingCrossings { SubRingCrossings() : valid(false) {} SubRingCrossings(int ci, int ni, float nd) : valid(true), closestIndex(ci), nextIndex(ni), nextDistance(nd) {} bool valid; int closestIndex; int nextIndex; float nextDistance; }; #endif bool condition(); #ifdef USE_OPTIONAL std::optional<SubRingCrossings> foo() { if (condition()) { return std::nullopt; } return SubRingCrossings(1, 2, 3.14); } #else SubRingCrossings foo() { if (condition()) { return SubRingCrossings(); } return SubRingCrossings(1, 2, 3.14); } #endif int bar() { auto tmp = foo(); #ifdef USE_OPTIONAL if (tmp) { return tmp->closestIndex; #else if (tmp.valid) { return tmp.closestIndex; #endif } else { return 0; } }