Stroustrup 提出了一个同步队列类 Sync_queue . (CPL,4,第 1232-1235 页)。
Sync_queue tester 给出以下编译错误:
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.
Sync_queue
类的相关部分(发生编译错误的地方)是一个包含 lambda 的方法,如下所示:
/** 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;
}
下面一行是第62行:
unsigned int min_size)
和第 69 行包含 lambda 作为 condition_variable
的 wait_for()
方法的谓词:
[this] {return q.size() < min_size;});
如何修复这个编译错误?
最佳答案
使用min_size
在 lambda 表达式中,您应该明确捕获它:
[this, min_size] {return q.size() < min_size;}
另一种选择是使用自动捕获,如 [&]
或 [=]
但一般来说,最好使用显式捕获来防止 lambda 产生意外的副作用。
有关详细说明,请参阅 cppreference on lambdas - 捕获元素。
关于c++ - Sync_queue 类编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50344016/