Commit d510a7c5 authored by jan.koester's avatar jan.koester
Browse files

optional: rvalue access returns the value, not T&&

operator*() && / const&& and value() && / const&& now return T by
value (moved, or copied for const&&) instead of a reference into the
optional. With the reference return, a range-for or a const reference
bound to the result of a function returning an optional dangles in C++20:

    for (auto x : *lookup())              // lookup() returns optional<vector>
    const auto &r = *lookup();

The range/reference binds into the temporary optional, which is destroyed
at the end of the full expression (only C++23's P2718 extends temporaries
in the range initializer). A prvalue return makes the language extend its
lifetime instead; the cost is one move. Types that can't be moved (or, for
const&&, copied) keep the reference return.

Found in mammut, where an index lookup loop read freed rowids.
New e2e test cxx_optional_rvalue_test.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 65ffa1f2
Loading
Loading
Loading
Loading
+23 −4
Changes for include/cxx/optional: 23 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -323,9 +323,28 @@ public:
    constexpr bool has_value() const noexcept { return _has; }
    constexpr explicit operator bool() const noexcept { return _has; }

    /* Rvalue access returns the value itself (moved out), not T&&.
     *
     * With T&& (the standard's signature) a range-for over the result of
     * a function returning an optional dangles in C++20:
     *
     *     for (auto x : *lookup())          // lookup() returns optional<vector>
     *
     * The range is bound as `auto&& __r = *lookup();` -- a reference into
     * the temporary optional, which is destroyed at the end of that full
     * expression, before the loop body runs (only C++23's P2718 extends
     * temporaries in the range initializer). The same holds for
     * `const T& r = *f();`. Returning a prvalue makes the language extend
     * its lifetime to the reference instead, so both forms are safe; the
     * cost is one move. Types that can't be moved (or, for const&&, copied)
     * keep the reference return. Found in mammut's index lookup, where the
     * loop read freed rowids. */
    using __rvalue_access = typename conditional<is_move_constructible<T>::value, T, T&&>::type;
    using __const_rvalue_access = typename conditional<is_copy_constructible<T>::value, T, const T&&>::type;

    constexpr T& value() & { if (!_has) __builtin_trap(); return _value(); }
    constexpr const T& value() const& { if (!_has) __builtin_trap(); return _value(); }
    constexpr T&& value() && { if (!_has) __builtin_trap(); return std::move(_value()); }
    constexpr __rvalue_access value() && { if (!_has) __builtin_trap(); return std::move(_value()); }
    /* Real gap found while comparing systempp's <cxx/ *> headers
     * against real llvm-project's libcxx: the const&&-qualified
     * overload was missing here (and on operator*()/and_then()/
@@ -334,7 +353,7 @@ public:
     * these, not just 3, matching how a const optional<T> rvalue
     * (e.g. a const-returning function's own temporary result) is
     * real, valid C++ to call value()/operator*() on. */
    constexpr const T&& value() const&& { if (!_has) __builtin_trap(); return std::move(_value()); }
    constexpr __const_rvalue_access value() const&& { if (!_has) __builtin_trap(); return std::move(_value()); }

    template<class U>
    constexpr T value_or(U&& def) const& { return _has ? _value() : static_cast<T>(std::forward<U>(def)); }
@@ -345,8 +364,8 @@ public:
    constexpr const T* operator->() const { return &_value(); }
    constexpr T& operator*() & { return _value(); }
    constexpr const T& operator*() const& { return _value(); }
    constexpr T&& operator*() && { return std::move(_value()); }
    constexpr const T&& operator*() const&& { return std::move(_value()); }
    constexpr __rvalue_access operator*() && { return std::move(_value()); }
    constexpr __const_rvalue_access operator*() const&& { return std::move(_value()); }

    void reset() noexcept { if (_has) { _value().~T(); _has = false; } }

+20 −0
Changes for src/test/e2e/CMakeLists.txt: 20 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -3890,6 +3890,26 @@ add_dependencies(e2e_cxx_reference_stability crti Scrt1 crtbeginS crtn systempp)

add_test(NAME e2e_cxx_reference_stability COMMAND e2e_cxx_reference_stability)

add_executable(e2e_cxx_optional_rvalue cxx_optional_rvalue_test.cpp)
set_target_properties(e2e_cxx_optional_rvalue PROPERTIES OUTPUT_NAME "cxx_optional_rvalue_test")
target_compile_options(e2e_cxx_optional_rvalue PRIVATE -fPIE)
target_link_options(e2e_cxx_optional_rvalue PRIVATE
    -nostdlib -pie
    -Wl,--hash-style=sysv
    -Wl,--dynamic-linker,$<TARGET_FILE_DIR:systempp>/ld-linux-${CMAKE_SYSTEM_PROCESSOR}.so
    -Wl,-rpath,$<TARGET_FILE_DIR:systempp>
)
target_link_libraries(e2e_cxx_optional_rvalue PRIVATE
    $<TARGET_OBJECTS:crti>
    $<TARGET_OBJECTS:Scrt1>
    $<TARGET_OBJECTS:crtbeginS>
    $<TARGET_OBJECTS:crtn>
    systempp
)
add_dependencies(e2e_cxx_optional_rvalue crti Scrt1 crtbeginS crtn systempp)

add_test(NAME e2e_cxx_optional_rvalue COMMAND e2e_cxx_optional_rvalue)

add_executable(e2e_cxx_copy_aliasing cxx_copy_aliasing_test.cpp)
set_target_properties(e2e_cxx_copy_aliasing PROPERTIES OUTPUT_NAME "cxx_copy_aliasing_test")
target_compile_options(e2e_cxx_copy_aliasing PRIVATE -fPIE)
+95 −0
Changes for src/test/e2e/cxx_optional_rvalue_test.cpp: 95 added lines, 0 removed lines.
Original line number Diff line number Diff line
/* std::optional rvalue access returns the value, not T&&: a range-for or a
 * const reference bound to *f() / f().value() must not dangle when f()
 * returns the optional by value (C++20 destroys that temporary at the end
 * of the full expression). Every element read below would come from freed
 * memory with a T&& return.
 */

#include <cstdio>
#include <optional>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

static int g_fail = 0;
#define CHECK(c, ...) do { if (!(c)) { std::printf("FAIL %s:%d: ", __FILE__, __LINE__); std::printf(__VA_ARGS__); std::printf("\n"); g_fail++; } } while (0)

static std::optional<std::vector<unsigned long>> lookup(unsigned long base) {
    std::vector<unsigned long> v;
    for (unsigned long i = 0; i < 64; i++) v.push_back(base + i);
    return v;
}

static const std::optional<std::string> constName() { return std::string("a string long enough to live on the heap"); }

// a type that can be neither copied nor moved keeps the reference return
struct Pinned {
    int v;
    explicit Pinned(int x) : v(x) {}
    Pinned(const Pinned&) = delete;
    Pinned(Pinned&&) = delete;
};

int main() {
    {   // range-for over *temporary
        unsigned long sum = 0, n = 0;
        for (unsigned long x : *lookup(1000)) {
            std::vector<unsigned long> clobber(64, 0xdeadbeef);   // reuses freed memory if the range dangles
            (void)clobber;
            sum += x;
            n++;
        }
        CHECK(n == 64, "range-for over *f(): %lu elements", n);
        CHECK(sum == 64 * 1000 + 2016, "range-for over *f(): sum %lu", sum);
    }
    {   // range-for over f().value()
        unsigned long n = 0, last = 0;
        for (unsigned long x : lookup(7).value()) { last = x; n++; }
        CHECK(n == 64 && last == 70, "range-for over f().value(): n=%lu last=%lu", n, last);
    }
    {   // const& bound to *f() / f().value()
        const std::vector<unsigned long>& r = *lookup(5);
        std::vector<unsigned long> clobber(64, 1);
        (void)clobber;
        CHECK(r.size() == 64 && r[0] == 5 && r[63] == 68, "const& to *f()");
        const std::string& s = *constName();
        CHECK(s == "a string long enough to live on the heap", "const& to *f() of a const optional");
        std::string&& m = lookup(1).value().empty() ? std::string() : std::string("x");
        CHECK(m == "x", "rvalue reference to a computed value");
    }
    {   // return types
        static_assert(std::is_same<decltype(*std::declval<std::optional<std::string>>()), std::string>::value,
                      "operator*() && returns the value");
        static_assert(std::is_same<decltype(std::declval<std::optional<std::string>>().value()), std::string>::value,
                      "value() && returns the value");
        static_assert(std::is_same<decltype(*std::declval<const std::optional<std::string>>()), std::string>::value,
                      "operator*() const&& returns a copy");
        static_assert(std::is_same<decltype(*std::declval<std::optional<std::string>&>()), std::string&>::value,
                      "lvalue access still returns a reference");
        static_assert(std::is_same<decltype(*std::declval<const std::optional<std::string>&>()), const std::string&>::value,
                      "const lvalue access still returns a reference");
        static_assert(std::is_same<decltype(*std::declval<std::optional<Pinned>>()), Pinned&&>::value,
                      "immovable types keep T&&");
    }
    {   // moving the value out still moves (the source is left moved-from)
        std::optional<std::string> o(std::string(100, 'z'));
        std::string taken = *std::move(o);
        CHECK(taken.size() == 100, "moved out: %zu", taken.size());
        CHECK(o.has_value() && o->empty(), "source moved-from, still engaged");
        std::optional<std::vector<int>> ov(std::vector<int>{1, 2, 3});
        std::vector<int> v = std::move(ov).value();
        CHECK(v.size() == 3 && ov->empty(), "value() && moves");
    }
    {   // in-place access through the lvalue overloads is unchanged
        std::optional<std::string> o("abc");
        *o += "def";
        o.value() += "!";
        CHECK(*o == "abcdef!", "lvalue access modifies in place: %s", o->c_str());
        std::optional<Pinned> p;
        p.emplace(9);
        CHECK(std::move(p)->v == 9 && (*std::move(p)).v == 9, "immovable value through operator*() &&");
    }
    if (g_fail == 0) std::printf("cxx_optional_rvalue_test: all passed\n");
    return g_fail ? 1 : 0;
}