c++ - sync_queue 类编译错误
问题描述
Stroustrup 提出了一个同步队列类Sync_queue。(CPL,4,第 1232-1235 页)。
Sync_queue测试器 给出以下编译错误:
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;}
另一种选择是使用自动捕获,例如[&]
or[=]
但通常最好使用显式捕获来防止您的 lambda 出现意外的副作用。有关详细说明,请参阅lambdas 上的 cppreference -捕获项目。
推荐阅读
- linux - crontab 无法删除文件夹
- reactjs - Google Drive上传文件rest api返回401错误
- cytoscape.js - 根据边的数据和目标的数据选择边
- node.js - 通过 node.js 将几何对象解析为 wkt
- c - 在行号出现中产生“3”的第一个索引的函数
- c++ - C++ clang 链接器命令失败,退出代码为 1
- python - 合并列以创建带有标题的日期
- django - 如何在 django 中添加为表单域
- php - 如果需要很长时间才能返回,php ajax调用不返回任何内容
- python - ProgressDialog和Dialog依次打开时Dialog不是模态的