This is an automated email from the ASF dual-hosted git repository.

chenBright pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/brpc.git


The following commit(s) were added to refs/heads/master by this push:
     new 6347867f7 fix: preserve optional value lifetime (#3724)
6347867f7 is described below

commit 6347867f764a33004dd547cfc8d3f8f030faee1c
Author: nkysg <[email protected]>
AuthorDate: Sat Nov 21 16:19:18 2026 +0800

    fix: preserve optional value lifetime (#3724)
    
    * fix: preserve optional value lifetime
    
    * Fix copy and move traits for C++14 optional
    
    * Fix converting optional move semantics
    
    * Fix optional swap noexcept specification
---
 .github/workflows/ci-linux.yml  |   7 ++
 src/butil/containers/optional.h | 194 ++++++++++++++++++++++++++++++++++------
 test/optional_unittest.cpp      | 151 ++++++++++++++++++++++++++++++-
 3 files changed, 323 insertions(+), 29 deletions(-)

diff --git a/.github/workflows/ci-linux.yml b/.github/workflows/ci-linux.yml
index 9dcadae32..eff5b4eab 100644
--- a/.github/workflows/ci-linux.yml
+++ b/.github/workflows/ci-linux.yml
@@ -387,6 +387,13 @@ jobs:
     - uses: ./.github/actions/init-ut-make-config
       with:
         options: --with-bthread-tracer --with-asan
+    - name: Test C++14 optional with sanitizers
+      run: |
+        clang++-12 -std=c++14 -DBRPC_TEST_OPTIONAL_CXX14 \
+          -fsanitize=address,undefined -fno-omit-frame-pointer -I src \
+          test/optional_unittest.cpp -lgtest_main -lgtest -pthread \
+          -o "$RUNNER_TEMP/optional-cxx14-unittest"
+        "$RUNNER_TEMP/optional-cxx14-unittest"
     - name: compile tests
       run: |
         cat config.mk
diff --git a/src/butil/containers/optional.h b/src/butil/containers/optional.h
index e19695849..4c44a727f 100644
--- a/src/butil/containers/optional.h
+++ b/src/butil/containers/optional.h
@@ -119,10 +119,136 @@ struct 
is_constructible_convertible_assignable_from_optional
         is_convertible_from_optional<T, U>::value ||
         is_assignable_from_optional<T, U>::value> {};
 
+template <bool enabled>
+struct OptionalCopyConstructible {};
+
+template <>
+struct OptionalCopyConstructible<false> {
+    OptionalCopyConstructible() = default;
+    OptionalCopyConstructible(const OptionalCopyConstructible&) = delete;
+    OptionalCopyConstructible(OptionalCopyConstructible&&) = default;
+    OptionalCopyConstructible& operator=(const OptionalCopyConstructible&) = 
default;
+    OptionalCopyConstructible& operator=(OptionalCopyConstructible&&) = 
default;
+};
+
+template <bool enabled>
+struct OptionalMoveConstructible {};
+
+template <>
+struct OptionalMoveConstructible<false> {
+    OptionalMoveConstructible() = default;
+    OptionalMoveConstructible(const OptionalMoveConstructible&) = default;
+    OptionalMoveConstructible(OptionalMoveConstructible&&) = delete;
+    OptionalMoveConstructible& operator=(const OptionalMoveConstructible&) = 
default;
+    OptionalMoveConstructible& operator=(OptionalMoveConstructible&&) = 
default;
+};
+
+template <bool enabled>
+struct OptionalCopyAssignable {};
+
+template <>
+struct OptionalCopyAssignable<false> {
+    OptionalCopyAssignable() = default;
+    OptionalCopyAssignable(const OptionalCopyAssignable&) = default;
+    OptionalCopyAssignable(OptionalCopyAssignable&&) = default;
+    OptionalCopyAssignable& operator=(const OptionalCopyAssignable&) = delete;
+    OptionalCopyAssignable& operator=(OptionalCopyAssignable&&) = default;
+};
+
+template <bool enabled>
+struct OptionalMoveAssignable {};
+
+template <>
+struct OptionalMoveAssignable<false> {
+    OptionalMoveAssignable() = default;
+    OptionalMoveAssignable(const OptionalMoveAssignable&) = default;
+    OptionalMoveAssignable(OptionalMoveAssignable&&) = default;
+    OptionalMoveAssignable& operator=(const OptionalMoveAssignable&) = default;
+    OptionalMoveAssignable& operator=(OptionalMoveAssignable&&) = delete;
+};
+
+template <typename T>
+class OptionalBase {
+public:
+    OptionalBase() : _engaged(false) {}
+
+    OptionalBase(const OptionalBase& rhs) : _engaged(false) {
+        if (rhs._engaged) {
+            _storage.Init(*rhs._storage);
+            _engaged = true;
+        }
+    }
+
+    OptionalBase(OptionalBase&& rhs) noexcept(
+        std::is_nothrow_move_constructible<T>::value) : _engaged(false) {
+        if (rhs._engaged) {
+            _storage.Init(std::move(*rhs._storage));
+            _engaged = true;
+        }
+    }
+
+    ~OptionalBase() { reset(); }
+
+    OptionalBase& operator=(const OptionalBase& rhs) {
+        if (this != &rhs) {
+            if (rhs._engaged) {
+                if (_engaged) {
+                    *_storage = *rhs._storage;
+                } else {
+                    _storage.Init(*rhs._storage);
+                    _engaged = true;
+                }
+            } else {
+                reset();
+            }
+        }
+        return *this;
+    }
+
+    OptionalBase& operator=(OptionalBase&& rhs) noexcept(
+        std::is_nothrow_move_constructible<T>::value &&
+        std::is_nothrow_move_assignable<T>::value) {
+        if (this != &rhs) {
+            if (rhs._engaged) {
+                if (_engaged) {
+                    *_storage = std::move(*rhs._storage);
+                } else {
+                    _storage.Init(std::move(*rhs._storage));
+                    _engaged = true;
+                }
+            } else {
+                reset();
+            }
+        }
+        return *this;
+    }
+
+protected:
+    void reset() {
+        if (_engaged) {
+            _storage.Destroy();
+            _engaged = false;
+        }
+    }
+
+    bool _engaged;
+    ManualConstructor<T> _storage;
+};
+
 } // namespace internal
 
 template<typename T>
-class optional {
+class optional : private internal::OptionalBase<T>,
+                 private internal::OptionalCopyConstructible<
+                     std::is_copy_constructible<T>::value>,
+                 private internal::OptionalMoveConstructible<
+                     std::is_move_constructible<T>::value>,
+                 private internal::OptionalCopyAssignable<
+                     std::is_copy_constructible<T>::value &&
+                     std::is_copy_assignable<T>::value>,
+                 private internal::OptionalMoveAssignable<
+                     std::is_move_constructible<T>::value &&
+                     std::is_move_assignable<T>::value> {
 public:
     typedef T value_type;
 
@@ -137,22 +263,24 @@ public:
     static_assert(!is_array<value_type>::value,
                   "Instantiation of optional with an array type is 
ill-formed");
 
-    optional() : _engaged(false) {}
+    optional() = default;
 
     optional(nullopt_t) : optional() {}
 
     optional(const optional& rhs) = default;
 
-    optional(optional&& rhs) noexcept = default;
+    optional(optional&& rhs) noexcept(
+        std::is_nothrow_move_constructible<T>::value) = default;
 
     template <typename U, std::enable_if_t<
         !std::is_same<T, U>::value &&
         std::is_constructible<T, const U&>::value &&
         !internal::is_constructible_convertible_from_optional<T, U>::value &&
         std::is_convertible<const U&, T>::value, bool> = false>
-    optional(const optional<U>& rhs) : _engaged(rhs.has_value()) {
-        if (_engaged) {
+    optional(const optional<U>& rhs) {
+        if (rhs) {
             _storage.Init(*rhs);
+            _engaged = true;
         }
     }
 
@@ -161,9 +289,10 @@ public:
         std::is_constructible<T, const U&>::value &&
         !internal::is_constructible_convertible_from_optional<T, U>::value &&
         !std::is_convertible<const U&, T>::value, bool> = false>
-    explicit optional(const optional<U>& rhs) : _engaged(rhs.has_value()) {
-        if (_engaged) {
+    explicit optional(const optional<U>& rhs) {
+        if (rhs) {
             _storage.Init(*rhs);
+            _engaged = true;
         }
     }
 
@@ -172,10 +301,10 @@ public:
         std::is_constructible<T, U&&>::value &&
         !internal::is_constructible_convertible_from_optional<T, U>::value &&
         std::is_convertible<U&&, T>::value, bool> = false>
-    optional(optional<U>&& rhs) : _engaged(rhs.has_value()) {
-        if (_engaged) {
+    optional(optional<U>&& rhs) {
+        if (rhs) {
             _storage.Init(std::move(*rhs));
-            rhs.reset();
+            _engaged = true;
         }
     }
 
@@ -184,33 +313,36 @@ public:
         std::is_constructible<T, U&&>::value &&
         !internal::is_constructible_convertible_from_optional<T, U>::value &&
         !std::is_convertible<U&&, T>::value, bool> = false>
-    explicit optional(optional<U>&& rhs) : _engaged(rhs.has_value()) {
-        if (_engaged) {
+    explicit optional(optional<U>&& rhs) {
+        if (rhs) {
             _storage.Init(std::move(*rhs));
-            rhs.reset();
+            _engaged = true;
         }
     }
 
-    optional(const T& value) : _engaged(true) {
+    optional(const T& value) {
         _storage.Init(value);
+        _engaged = true;
     }
 
-    optional(T&& value) : _engaged(true) {
+    optional(T&& value) {
         _storage.Init(std::move(value));
+        _engaged = true;
     }
 
     template <typename... Args, std::enable_if_t<
         std::is_constructible<T, Args&&...>::value, bool> = false>
-    explicit optional(in_place_t, Args&&... args) : _engaged(true) {
+    explicit optional(in_place_t, Args&&... args) {
         _storage.Init(std::forward<Args>(args)...);
+        _engaged = true;
     }
 
     template <typename U, typename... Args, std::enable_if_t<
         std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value,
         bool> = false>
-    optional(in_place_t, std::initializer_list<U> il, Args&&... args)
-        : _engaged(true) {
+    optional(in_place_t, std::initializer_list<U> il, Args&&... args) {
         _storage.Init(il, std::forward<Args>(args)...);
+        _engaged = true;
     }
 
     template <typename U = T, std::enable_if_t<
@@ -218,8 +350,9 @@ public:
         !std::is_same<optional<T>, typename std::decay<U>::type>::value &&
         std::is_constructible<T, U&&>::value &&
         std::is_convertible<U&&, T>::value, bool> = false>
-    optional(U&& v) : _engaged(true) {
+    optional(U&& v) {
         _storage.Init(std::forward<U>(v));
+        _engaged = true;
     }
 
     template <typename U = T, std::enable_if_t<
@@ -227,13 +360,12 @@ public:
         !std::is_same<optional<T>, typename std::decay<U>::type>::value &&
         std::is_constructible<T, U&&>::value &&
         !std::is_convertible<U&&, T>::value, bool> = false>
-    explicit optional(U&& v) : _engaged(true) {
+    explicit optional(U&& v) {
         _storage.Init(std::forward<U>(v));
+        _engaged = true;
     }
 
-    ~optional() {
-        reset();
-    }
+    ~optional() = default;
 
     optional& operator=(nullopt_t) noexcept {
         reset();
@@ -242,7 +374,9 @@ public:
 
     optional& operator=(const optional& rhs) = default;
 
-    optional& operator=(optional&& rhs) = default;
+    optional& operator=(optional&& rhs) noexcept(
+        std::is_nothrow_move_constructible<T>::value &&
+        std::is_nothrow_move_assignable<T>::value) = default;
 
     // Value assignment operators
     template <typename U = T, typename = std::enable_if_t<
@@ -362,7 +496,9 @@ public:
             std::move(**this) : static_cast<T>(std::forward<U>(v));
     }
 
-    void swap(optional& rhs) noexcept {
+    void swap(optional& rhs) noexcept(
+        std::is_nothrow_move_constructible<T>::value &&
+        std::is_nothrow_move_assignable<T>::value) {
         if (_engaged && rhs._engaged) {
             std::swap(**this, *rhs);
         } else if (_engaged) {
@@ -402,12 +538,14 @@ public:
     }
 
 private:
-    bool _engaged;
-    ManualConstructor<T> _storage;
+    using internal::OptionalBase<T>::_engaged;
+    using internal::OptionalBase<T>::_storage;
 };
 
 template <typename T>
-void swap(optional<T>& a, optional<T>& b) noexcept { a.swap(b); }
+void swap(optional<T>& a, optional<T>& b) noexcept(noexcept(a.swap(b))) {
+    a.swap(b);
+}
 
 // Creates a non-empty 'optional<T>`.
 template <typename T>
diff --git a/test/optional_unittest.cpp b/test/optional_unittest.cpp
index 8038105c7..bb15af3de 100644
--- a/test/optional_unittest.cpp
+++ b/test/optional_unittest.cpp
@@ -17,14 +17,40 @@
 
 
 #include <gtest/gtest.h>
+#include <memory>
+#include <type_traits>
+#include <utility>
 #include "butil/containers/optional.h"
 
+#if defined(BRPC_TEST_OPTIONAL_CXX14) && __cplusplus != 201402L
+#error "The C++14 optional test must use the C++14 implementation"
+#endif
+
 namespace {
 
 butil::optional<int> empty_optional() {
     return {};
 }
 
+struct LifetimeTracker {
+    static int live;
+    static int constructed;
+    static int destroyed;
+
+    LifetimeTracker() { ++live; ++constructed; }
+    LifetimeTracker(const LifetimeTracker&) { ++live; ++constructed; }
+    LifetimeTracker(LifetimeTracker&&) { ++live; ++constructed; }
+    LifetimeTracker& operator=(const LifetimeTracker&) { return *this; }
+    LifetimeTracker& operator=(LifetimeTracker&&) { return *this; }
+    ~LifetimeTracker() { --live; ++destroyed; }
+
+    static void Reset() { live = constructed = destroyed = 0; }
+};
+
+int LifetimeTracker::live = 0;
+int LifetimeTracker::constructed = 0;
+int LifetimeTracker::destroyed = 0;
+
 TEST(OptionalTest, sanity) {
     {
         butil::optional<int> empty;
@@ -86,6 +112,15 @@ TEST(OptionalTest, copy) {
     non_empty = op;
     ASSERT_TRUE(non_empty);
     ASSERT_EQ(10, non_empty);
+
+    const std::string value(128, 'x');
+    butil::optional<std::string> string_source(value);
+    butil::optional<std::string> string_copied(string_source);
+    ASSERT_EQ(value, *string_source);
+    ASSERT_EQ(value, *string_copied);
+
+    string_copied = string_source;
+    ASSERT_EQ(value, *string_copied);
 }
 
 TEST(OptionalTest, move) {
@@ -105,6 +140,102 @@ TEST(OptionalTest, move) {
     butil::optional<int> empty_move_assign;
     empty_move_assign = std::move(empty);
     ASSERT_FALSE(empty_move_assign);
+
+    butil::optional<std::string> string_source(std::string(128, 'x'));
+    butil::optional<std::string> string_moved(std::move(string_source));
+    ASSERT_TRUE(string_source);
+    ASSERT_EQ(std::string(128, 'x'), *string_moved);
+
+    butil::optional<std::string> string_move_source(std::string(128, 'y'));
+    string_moved = std::move(string_move_source);
+    ASSERT_TRUE(string_move_source);
+    ASSERT_TRUE(string_moved);
+    ASSERT_EQ(std::string(128, 'y'), *string_moved);
+}
+
+TEST(OptionalTest, nontrivial_lifetime) {
+    LifetimeTracker::Reset();
+    {
+        butil::optional<LifetimeTracker> source(butil::in_place);
+        butil::optional<LifetimeTracker> copied(source);
+        butil::optional<LifetimeTracker> moved(std::move(source));
+        butil::optional<LifetimeTracker> assigned;
+        assigned = copied;
+        assigned = butil::nullopt;
+    }
+    ASSERT_EQ(0, LifetimeTracker::live);
+    ASSERT_EQ(LifetimeTracker::constructed, LifetimeTracker::destroyed);
+}
+
+TEST(OptionalTest, nontrivial_assignment_states) {
+    const std::string value(128, 'x');
+    butil::optional<std::string> source(value);
+    butil::optional<std::string> empty;
+    butil::optional<std::string> target;
+
+    target = empty;
+    ASSERT_FALSE(target);
+    target = source;
+    ASSERT_EQ(value, *target);
+    target = source;
+    ASSERT_EQ(value, *target);
+    target = empty;
+    ASSERT_FALSE(target);
+
+    target = std::move(empty);
+    ASSERT_FALSE(target);
+    target = std::move(source);
+    ASSERT_EQ(value, *target);
+    source = value;
+    target = std::move(source);
+    ASSERT_EQ(value, *target);
+    target = std::move(empty);
+    ASSERT_FALSE(target);
+}
+
+TEST(OptionalTest, move_only_value) {
+    butil::optional<std::unique_ptr<int>> source(std::unique_ptr<int>(new 
int(42)));
+    butil::optional<std::unique_ptr<int>> moved(std::move(source));
+    ASSERT_EQ(42, **moved);
+    butil::optional<std::unique_ptr<int>> assigned;
+    assigned = std::move(moved);
+    ASSERT_EQ(42, **assigned);
+}
+
+struct CopyConstructOnly {
+    CopyConstructOnly() = default;
+    CopyConstructOnly(const CopyConstructOnly&) = default;
+    CopyConstructOnly(CopyConstructOnly&&) = delete;
+    CopyConstructOnly& operator=(const CopyConstructOnly&) = delete;
+    CopyConstructOnly& operator=(CopyConstructOnly&&) = delete;
+};
+
+struct AssignOnly {
+    AssignOnly() = default;
+    AssignOnly(const AssignOnly&) = delete;
+    AssignOnly(AssignOnly&&) = delete;
+    AssignOnly& operator=(const AssignOnly&) = default;
+    AssignOnly& operator=(AssignOnly&&) = default;
+};
+
+TEST(OptionalTest, copy_move_traits_follow_value_type) {
+    using MoveOnly = butil::optional<std::unique_ptr<int>>;
+    static_assert(!std::is_copy_constructible<MoveOnly>::value, "");
+    static_assert(!std::is_copy_assignable<MoveOnly>::value, "");
+    static_assert(std::is_move_constructible<MoveOnly>::value, "");
+    static_assert(std::is_move_assignable<MoveOnly>::value, "");
+
+    using CopyOnly = butil::optional<CopyConstructOnly>;
+    static_assert(std::is_copy_constructible<CopyOnly>::value, "");
+    static_assert(std::is_move_constructible<CopyOnly>::value, "");
+    static_assert(!std::is_copy_assignable<CopyOnly>::value, "");
+    static_assert(!std::is_move_assignable<CopyOnly>::value, "");
+
+    using NoConstruction = butil::optional<AssignOnly>;
+    static_assert(!std::is_copy_constructible<NoConstruction>::value, "");
+    static_assert(!std::is_move_constructible<NoConstruction>::value, "");
+    static_assert(!std::is_copy_assignable<NoConstruction>::value, "");
+    static_assert(!std::is_move_assignable<NoConstruction>::value, "");
 }
 
 struct Obj {};
@@ -152,10 +283,12 @@ TEST(OptionalTest, convert) {
         ASSERT_TRUE(opt_copy->default_ctor);
         ASSERT_FALSE(opt_copy->move_ctor);
 
-        butil::optional<Convert> opt_move(butil::optional<Obj>{ 
butil::in_place });
+        butil::optional<Obj> move_source(butil::in_place);
+        butil::optional<Convert> opt_move(std::move(move_source));
         ASSERT_TRUE(opt_move);
         ASSERT_TRUE(opt_move->default_ctor);
         ASSERT_TRUE(opt_move->move_ctor);
+        ASSERT_TRUE(move_source);
     }
 
     {
@@ -224,6 +357,22 @@ TEST(OptionalTest, swap) {
     ASSERT_TRUE(noexcept(swap(opt1, opt2)));
 }
 
+struct ThrowingMove {
+    ThrowingMove() = default;
+    ThrowingMove(const ThrowingMove&) = default;
+    ThrowingMove(ThrowingMove&&) noexcept(false) { }
+    ThrowingMove& operator=(const ThrowingMove&) = default;
+    ThrowingMove& operator=(ThrowingMove&&) noexcept(false) { return *this; }
+};
+
+TEST(OptionalTest, swap_noexcept_follows_value_type) {
+    using Optional = butil::optional<ThrowingMove>;
+    static_assert(!noexcept(std::declval<Optional&>().swap(
+                      std::declval<Optional&>())), "");
+    static_assert(!noexcept(swap(std::declval<Optional&>(),
+                                 std::declval<Optional&>())), "");
+}
+
 TEST(OptionalTest, make_optional) {
     auto opt_int = butil::make_optional(1);
     ASSERT_TRUE((std::is_same<decltype(opt_int), 
butil::optional<int>>::value));


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to