本文介绍了在tbb :: concurrent_hash_map中使用std :: unique_ptr作为值时的编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用 tbb :: concurrent_hash_map 替换 std :: unordered_map

我的原始代码:

typedef std::unique_ptr<V> V_ptr;

std::unordered_map<K, V_ptr> hm;
V_ptr v (new V);
K k;

hm.insert (std::make_pair (k, std::move (v)));

使用clang 3.3编译良好。将unordered_map切换为concurrent_hash_map:

compiles fine with clang 3.3. Switching the unordered_map to a concurrent_hash_map:

typedef std::unique_ptr<V> V_ptr;

tbb::concurrent_hash_map<K, V_ptr> hm;
V_ptr v (new V);
K k;

hm.insert (std::make_pair (k, std::move (v)));

会导致错误: ... stl_pair.h:105:21 :error:call to deleted constructor of
'std :: unique_ptr< ...

?我记得在gcc 4.5中有类似的错误在许多容器中使用std :: unique_ptrs。 (上面的原始代码不会用gcc 4.5编译ex。)或者也许我错过了关于concurrent_hash_maps的内容?

Is this a bug in clang 3.3? I remember there being similar errors in gcc 4.5 when using std::unique_ptrs in many containers. (The above original code will not compile with gcc 4.5 for ex.) Or maybe I missed something about concurrent_hash_maps?

推荐答案

文档仅通过触发 unique_ptr 的复制的 const& 进行参数:

According to documentation tbb::concurrent_hash_map takes argument only via const& which triggers copy of unique_ptr:

bool insert( const value_type& value );

作为解决方法,您可以使用 std :: shared_ptr 或将 unique_ptr 存储在独立向量中:

As workaround you may use std::shared_ptr or store unique_ptrs in stand-alone vector:

std::vector<std::unique_ptr<V>> ptrs;

并将原始指针存储在 concurrent_hash_map 中。

and store raw pointers in concurrent_hash_map. Though, that may be not acceptable for your use cases (like frequent deletions).

另一种可能性是使用 std :: auto_ptr 或类似的东西。但这是危险的 - 正确的副本应该到达桶,所以你必须测试它。

Another possibility is to use std::auto_ptr or something similar. But that is dangerous - right copy should arrive into bucket, so you have to test it.

这篇关于在tbb :: concurrent_hash_map中使用std :: unique_ptr作为值时的编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 22:05