#393·oneTBB

Porting from tbb::task to tbb::task_group for non-const execute() methods?

Author: e4lamCreated May 8, 2021Updated Sep 1, 2026
Labelsenhancement

In the old tbb::task API, execute() methods were not marked as const. Therefore, it could mutate state within itself. This was often just needed for the duration of the execute method. eg. for calling different non-const methods on an data member that it owned.

In the oneTBB migration docs, it suggests that we use functors instead with tbb::task_group. However, a naïve conversion does not work since the operator() of the functor is required to be const (even though there seems to be no documentation to that effect). A contrived example that fails to compile: https://godbolt.org/z/jTxoh8dqn

#include <tbb/task_group.h>

struct Functor
{
    int x_ = 0;
#if 1
    void operator()() { ++x_; } // this fails 
#else
    void operator()() const { } // this works
#endif
};

int main()
{
    tbb::task_group tg;
    tg.run_and_wait(Functor{});
    return 0;
}