构造函数中的lambda实例化(lambda instantiation in constructor)
我有这样一个构造函数:
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>()’我怎样才能克服这个问题?
I have such a constructor:
ConcurrentHashMap(int expected_size, int expected_threads_count, const Hash& hasher = Hash()) { this->my_hash_ = hasher; if (expected_size != kUndefinedSize) table.reserve(expected_size); }When I pass a lambda function for the hasher argument:
auto lambda = [](const std::pair<int, int>& x) { return pair_hash(x); };I get the errors:
: 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 hereAnd:
error: use of deleted function ‘Correctness_Constructors_Test::TestBody()::<lambda(const std::pair<int, int>&)>::<lambda>()’How can I overcome this problem?
最满意答案
这里的问题是你在构造函数成员初始化列表中默认构造my_hash_ (因为你没有提供),然后你在构造函数体中分配它。 由于my_hash_是一个lambda,因此它不是默认构造的,因为lambdas不是默认构造的。 您需要在成员初始化列表中初始化my_hash_ ,如
ConcurrentHashMap(int expected_size, int expected_threads_count, const Hash& hasher = Hash()) : my_hash_(hasher) { //... }The issue here is you default construct my_hash_ in your constructor member initialization list (because you do not provide one) and then you assign to it in the constructor body. Since my_hash_ is a lambda it is not default constructable as lambdas are not default constructable. You need to initialize my_hash_ in the member initializer list like
ConcurrentHashMap(int expected_size, int expected_threads_count, const Hash& hasher = Hash()) : my_hash_(hasher) { //... }更多推荐
发布评论