Lambda构造函数中的实例化

lambda instantiation in constructor

本文关键字:实例化 构造函数 Lambda      更新时间:2023-10-16

我有这样的构造函数:

ConcurrentHashMap(int expected_size, int expected_threads_count, const Hash& hasher = Hash())
    {
      this->my_hash_ = hasher;
      if (expected_size != kUndefinedSize)
         table.reserve(expected_size);
    }

当我通过 hasher参数的lambda函数时:

auto lambda = [](const std::pair<int, int>& x) {
    return pair_hash(x);
};

我得到错误:

: In instantiation of ‘ConcurrentHashMap<K, V, Hash>::ConcurrentHashMap(int, int, const Hash&) [with K = std::pair<int, int>; V = std::__cxx11::basic_string<char>; Hash = Correctness_Constructors_Test::TestBody()::<lambda(const std::pair<int, int>&)>]’:
   required from here

和:

error: use of deleted function ‘Correctness_Constructors_Test::TestBody()::<lambda(const std::pair<int, int>&)>::<lambda>()’

如何克服这个问题?

这里的问题是您在构造函数成员初始化列表中默认构造 my_hash_(因为您不提供一个),然后在构造函数正文中分配给它。由于my_hash_是lambda,因此无法构造默认值,因为lambdas无法构造。您需要在成员初始化列表中初始化my_hash_,例如

ConcurrentHashMap(int expected_size, int expected_threads_count, 
                  const Hash& hasher = Hash()) : my_hash_(hasher)
{
    //...
}