首页 > 解决方案 > 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;});


如何修复此编译错误?

标签: c++multithreading

解决方案


min_size在 lambda 表达式中使用,您应该显式捕获它:

[this, min_size] {return q.size() < min_size;}

另一种选择是使用自动捕获,例如[&]or[=]但通常最好使用显式捕获来防止您的 lambda 出现意外的副作用。有关详细说明,请参阅lambdas 上的 cppreference -捕获项目。


推荐阅读