Skip to content

Commit a8db2de

Browse files
authored
Fix cuda::constant_iterator (#8260)
We incorrectly returned `const _Tp&` from `operator*` and `operator[]` This can lead to dangling references in pretty common code, such as `cuda::std::reverse_iterator` which does a `return *::cuda::std::prev(__current_);` The temporary created by `::cuda::std::prev(__current_)` is then dangling because we returned a reference to the value stored in the temporary iterator
1 parent 4889f70 commit a8db2de

File tree

3 files changed

+8
-8
lines changed

3 files changed

+8
-8
lines changed

libcudacxx/include/cuda/__iterator/constant_iterator.h

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,14 +130,14 @@ class constant_iterator
130130
return static_cast<difference_type>(__index());
131131
}
132132

133-
//! @brief Returns a const reference to the stored value
134-
[[nodiscard]] _CCCL_API constexpr const _Tp& operator*() const noexcept
133+
//! @brief Returns the stored value
134+
[[nodiscard]] _CCCL_API constexpr reference operator*() const noexcept
135135
{
136136
return __value();
137137
}
138138

139-
//! @brief Returns a const reference to the stored value
140-
[[nodiscard]] _CCCL_API constexpr const _Tp& operator[](difference_type) const noexcept
139+
//! @brief Returns the stored value
140+
[[nodiscard]] _CCCL_API constexpr reference operator[](difference_type) const noexcept
141141
{
142142
return __value();
143143
}

libcudacxx/test/libcudacxx/cuda/iterators/constant_iterator/star.pass.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,14 @@ __host__ __device__ constexpr void test(T value)
2727
}
2828

2929
static_assert(noexcept(*iter));
30-
static_assert(cuda::std::is_same_v<decltype(*iter), const T&>);
30+
static_assert(cuda::std::is_same_v<decltype(*iter), T>);
3131
}
3232

3333
{
3434
const cuda::constant_iterator iter{value, 42};
3535
assert(*iter == value);
3636
static_assert(noexcept(*iter));
37-
static_assert(cuda::std::is_same_v<decltype(*iter), const T&>);
37+
static_assert(cuda::std::is_same_v<decltype(*iter), T>);
3838
}
3939
}
4040

libcudacxx/test/libcudacxx/cuda/iterators/constant_iterator/subscript.pass.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ __host__ __device__ constexpr void test(T value)
2727
}
2828

2929
static_assert(noexcept(iter[42]));
30-
static_assert(cuda::std::is_same_v<decltype(iter[42]), const T&>);
30+
static_assert(cuda::std::is_same_v<decltype(iter[42]), T>);
3131
}
3232

3333
{
@@ -37,7 +37,7 @@ __host__ __device__ constexpr void test(T value)
3737
assert(iter[i] == value);
3838
}
3939
static_assert(noexcept(iter[42]));
40-
static_assert(cuda::std::is_same_v<decltype(iter[42]), const T&>);
40+
static_assert(cuda::std::is_same_v<decltype(iter[42]), T>);
4141
}
4242
}
4343

0 commit comments

Comments
 (0)