Stroustrup has presented a synchronized queue class Sync_queue. (CPL, 4, pp 1232-1235).
The Sync_queue tester gives the following compilation errors:
In file included from main.cpp:9:
./Sync_queue.h:69:47: error: variable 'min_size' cannot be implicitly captured in a lambda with no capture-default specified
[this] {return q.size() < min_size;});
^
./Sync_queue.h:62:23: note: 'min_size' declared here
unsigned int min_size)
^
./Sync_queue.h:69:21: note: lambda expression begins here
[this] {return q.size() < min_size;});
^
1 error generated.
The relevant portion of the Sync_queue class (where the compilation errors occur) is a method containing a lambda, shown below:
/** During a duration d, if the queue size
falls below a minimum level,
put a value onto the queue. */
template<typename T>
bool Sync_queue<T>::put(
T val,
std::chrono::steady_clock::duration d,
unsigned int min_size)
{
std::unique_lock<std::mutex> lck {mtx};
bool low = cnd.wait_for(
lck,
d,
[this] {return q.size() < min_size;});
if (low)
{
q.push_back(val);
cnd.notify_one();
}
else
{
cnd.notify_all();
}
return low;
}
The following line is line 62:
unsigned int min_size)
and line 69 contains the lambda as a predicate to the condition_variable's wait_for() method:
[this] {return q.size() < min_size;});
How do I fix this compilation error?
To use min_size inside a lambda expression you should explicitly capture it:
[this, min_size] {return q.size() < min_size;}
Another option would be to use automatic captures like [&] or [=] but in general it's better to use explicit captures to prevent your lambda from unexpected side effects.
For detailed explanation see cppreference on lambdas - captures item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With