c++ - Sync_queue 类编译错误

标签 c++ multithreading

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_variablewait_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/

相关文章:

c++ - 构建 BGSLibrary 失败(使用 OpenCV)

java - 可以将 main() 转换为守护线程

java - 文件排序 - 扫描仪 - java.util.NoSuchElementException

c++ - 从文件发出读取变量

c++ - gdb 调试 valgrind 未检测到的双重释放(?)

c++ - 我可以从 std::visit 返回 auto 吗?

multithreading - 如何确保线程之间唯一的本地状态以进行电子邮件队列处理

c++ - 了解从二进制文件中提取频率以创建哈夫曼树的逻辑

java - 如何在两个for循环中分别使用postDelayed或sleep两次

c++ - std::atomic 与非原子变量的性能如何?