C++11 std::atomic作为std::map的值
我想在映射中使用原子变量。我正在使用Visual Studio 2012(msvc-11)和gcc 4.7。我定义了一种类型:C++11 std::atomic作为std::map的值,c++11,dictionary,visual-studio-2012,gcc,atomic,C++11,Dictionary,Visual Studio 2012,Gcc,Atomic,我想在映射中使用原子变量。我正在使用Visual Studio 2012(msvc-11)和gcc 4.7。我定义了一种类型: typedef std::map<uint64_t, std::atomic<int64_t>> value_map_t; 产生错误: 错误C2248:std::atomic::atomic:无法访问类std::atomic gcc 4.7()也有同样的情况 错误:使用已删除的函数std::atomic::atomic(const std::a
typedef std::map<uint64_t, std::atomic<int64_t>> value_map_t;
产生错误:
错误C2248:std::atomic::atomic
:无法访问类std::atomic
gcc 4.7()也有同样的情况
错误:使用已删除的函数std::atomic::atomic(const std::atomic&)
然而,在VisualStudio2013(msvc-12)及更高版本中,以及在GCC4.8及更新版本中,它运行良好
你自己看看,然后
我在MSVC-11/GCC 4.7中能做什么使它有效?< P>我没有访问Visual C++编译器的能力,但我猜想下面的方法可能会起作用。使用间接寻址,利用映射到
atomic
s的(智能)指针:
#include <atomic>
#include <map>
#include <memory>
using atomic_ptr_t = std::shared_ptr<std::atomic<int64_t>>;
typedef std::map<uint64_t, atomic_ptr_t> value_map_t;
int main()
{
value_map_t map;
map[1] = atomic_ptr_t(new std::atomic<int64_t>(0));
return 0;
}
#包括
#包括
#包括
使用原子_ptr_t=std::shared_ptr;
typedef std::map value\u map\t;
int main()
{
价值地图;
map[1]=atomic_ptr_t(新std::atomic(0));
返回0;
}
在@Yam Marcovic的提示下,我在Visual Studio 2012中找到了如何执行此操作:
#include <atomic>
#include <map>
#include <tuple>
typedef std::atomic<int64_t> value_t;
typedef std::map<uint64_t, value_t> atomic_map_t;
int main()
{
int64_t in = 5;
atomic_map_t map;
map.emplace(std::piecewise_construct,
std::forward_as_tuple(1), std::forward_as_tuple(in));
auto it = map.find(1);
int64_t out = it->second.load();
return 0;
}
#包括
#包括
#包括
typedef std::原子值;
typedef std::映射原子映射;
int main()
{
int64_t in=5;
原子地图;
地图安放(标准::分段构造,
std::forward_as_元组(1),std::forward_as_元组(in));
autoit=map.find(1);
int64\u t out=it->second.load();
返回0;
}
它确实有效。不过,为了提高效率,避免在每次插入时使用额外的new(),以及为了提取而使用.get()。我想知道新的编译器是如何解决这个问题的?@VladimirShutow我完全同意你的看法。再说一遍,我没有访问此编译器的权限。抱歉。如果您想测试它,我在问题中提到了在线gcc 4.7.3编译器,但已经感谢您提供了此解决方案。问题似乎是此类编译器尚未实现足够的C++11,例如,它允许map::operator[]
仅默认构造映射项,不需要任何复制/移动构造函数。std::atomic
是C++11的一个特性,除非您愿意使用一个为C++11提供强大支持的编译器,否则您可能不希望这些功能工作得很好。GCC4.7和msvc-11在这方面都不太稳定。这在2021年起作用吗?
#include <atomic>
#include <map>
#include <tuple>
typedef std::atomic<int64_t> value_t;
typedef std::map<uint64_t, value_t> atomic_map_t;
int main()
{
int64_t in = 5;
atomic_map_t map;
map.emplace(std::piecewise_construct,
std::forward_as_tuple(1), std::forward_as_tuple(in));
auto it = map.find(1);
int64_t out = it->second.load();
return 0;
}