Use perfect-forwarding references to prevent passing temporaries

Without this change, it is easy to pass a temporary, for example a vector
returned by a function to ParallelFor(). With this commit a type-constraint
is added to disable the use of this function for rvalue sequences.

An alternative would have been to capture rvalue-references in the function,
but that would have made the function unnecessarily complex, involving tuple-capture
and `shared_ptr`s, while it is usually easy to control lifetime at the call-site.
This commit is contained in:
Johannes Schmidt 2026-03-12 14:12:00 +01:00
parent eb97638743
commit 907f41bae4

View file

@ -67,15 +67,14 @@ public:
void Join(bool stop = false);
template<typename VectorType, typename FuncType>
void ParallelFor(const VectorType& items, const FuncType& func)
void ParallelFor(VectorType&& items, const FuncType& func)
{
ParallelFor(items, true, func);
ParallelFor(std::forward<VectorType>(items), true, func);
}
template<typename VectorType, typename FuncType>
void ParallelFor(const VectorType& items, bool preChunk, const FuncType& func)
template<typename VectorType, typename FuncType, typename = std::enable_if_t<!std::is_rvalue_reference_v<VectorType&&>>>
void ParallelFor(VectorType&& items, bool preChunk, const FuncType& func)
{
const auto totalCount = std::size(items);
using SizeType = std::remove_const_t<decltype(totalCount)>;
const auto chunks = preChunk ? m_ThreadCount : totalCount;