Skip to content

Commit 907f41b

Browse files
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.
1 parent eb97638 commit 907f41b

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

lib/base/workqueue.hpp

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,15 +67,14 @@ class WorkQueue
6767
void Join(bool stop = false);
6868

6969
template<typename VectorType, typename FuncType>
70-
void ParallelFor(const VectorType& items, const FuncType& func)
70+
void ParallelFor(VectorType&& items, const FuncType& func)
7171
{
72-
ParallelFor(items, true, func);
72+
ParallelFor(std::forward<VectorType>(items), true, func);
7373
}
7474

75-
template<typename VectorType, typename FuncType>
76-
void ParallelFor(const VectorType& items, bool preChunk, const FuncType& func)
75+
template<typename VectorType, typename FuncType, typename = std::enable_if_t<!std::is_rvalue_reference_v<VectorType&&>>>
76+
void ParallelFor(VectorType&& items, bool preChunk, const FuncType& func)
7777
{
78-
7978
const auto totalCount = std::size(items);
8079
using SizeType = std::remove_const_t<decltype(totalCount)>;
8180
const auto chunks = preChunk ? m_ThreadCount : totalCount;

0 commit comments

Comments
 (0)