Skip to content

Commit

Permalink
Fix thrust::optional<T&>::emplace() (#1707)
Browse files Browse the repository at this point in the history
Where optional<T> inherits optional<T>::construct via a series
of classes, optional<T&> does not. This means that
optional<T&>::emplace() was broken and called into a member function
that did not exist.

This replaces the functionality to make optional<T&>::emplace() change
the stored reference to the new one. Note that it does _not_ emplace
the referee, as this would lead to questionable behavior when the
optional holds nullopt.

This was revealed by a change in LLVM, see
llvm/llvm-project#90152 and
ROCm/rocThrust#404.
  • Loading branch information
Snektron authored May 6, 2024
1 parent bda02da commit 717366f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#include <thrust/optional.h>

#include <unittest/unittest.h>

int main()
{
{
int a = 10;

thrust::optional<int&> maybe(a);

int b = 20;
maybe.emplace(b);

ASSERT_EQUAL(maybe.value(), 20);
// Emplacing with b shouldn't change a
ASSERT_EQUAL(a, 10);

int c = 30;
maybe.emplace(c);

ASSERT_EQUAL(maybe.value(), 30);
ASSERT_EQUAL(b, 20);
}

{
thrust::optional<int&> maybe;

int b = 21;
maybe.emplace(b);

ASSERT_EQUAL(maybe.value(), 21);

int c = 31;
maybe.emplace(c);

ASSERT_EQUAL(maybe.value(), 31);
ASSERT_EQUAL(b, 21);
}
}
10 changes: 4 additions & 6 deletions thrust/thrust/optional.h
Original file line number Diff line number Diff line change
Expand Up @@ -2778,13 +2778,11 @@ class optional<T&>
///
/// \group emplace
_CCCL_EXEC_CHECK_DISABLE
template <class... Args>
_CCCL_HOST_DEVICE T& emplace(Args&&... args) noexcept
template <class U>
_CCCL_HOST_DEVICE T& emplace(U& u) noexcept
{
static_assert(std::is_constructible<T, Args&&...>::value, "T must be constructible with Args");

*this = nullopt;
this->construct(std::forward<Args>(args)...);
m_value = thrust::addressof(u);
return *m_value;
}

/// Swaps this optional with the other.
Expand Down

0 comments on commit 717366f

Please sign in to comment.