Skip to content

Commit

Permalink
[OptionalReference] value_or() should not be callable with r-values
Browse files Browse the repository at this point in the history
Detected by clang-tidy-19's `bugprone-return-const-ref-from-parameter`
  • Loading branch information
alexkaratarakis committed Dec 5, 2024
1 parent 5cf9bee commit 803035d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
7 changes: 5 additions & 2 deletions include/fixed_containers/optional_reference.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <compare>
#include <memory>
#include <optional>
#include <type_traits>

namespace fixed_containers
{
Expand Down Expand Up @@ -86,11 +87,13 @@ class OptionalReference
return *val();
}

[[nodiscard]] constexpr reference value_or(reference default_value) const&
template <class U>
[[nodiscard]] constexpr reference value_or(U&& default_value) const&
requires(std::is_lvalue_reference_v<U>)
{
if (!has_value())
{
return default_value;
return std::forward<U>(default_value);
}

return *val();
Expand Down
20 changes: 20 additions & 0 deletions test/optional_reference_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,15 @@ TEST(OptionalReference, Value)
}
}

namespace
{
template <typename T, typename Parameter>
constexpr bool value_or_is_callable_with_rvalue()
{
return requires(T instance) { instance.value_or(Parameter{}); };
}
} // namespace

TEST(OptionalReference, ValueOr)
{
{
Expand All @@ -118,6 +127,17 @@ TEST(OptionalReference, ValueOr)
const int& result = val1.value_or(fallback_value);
EXPECT_EQ(5, result);
}
{
/*
constexpr int ENTRY_1 = 5;
const OptionalReference<const int> val1(ENTRY_1);
const int& result = val1.value_or(77); // This should fail to compile
EXPECT_EQ(5, result);
*/

static_assert(!value_or_is_callable_with_rvalue<OptionalReference<const int>, int>(),
"`value_or() should not be callable with r-values");
}
}

TEST(OptionalReference, DereferenceOperator)
Expand Down

0 comments on commit 803035d

Please sign in to comment.