2017-06-14 117 views
0

考虑这个简单的代码:解析的外部符号 “的std :: atomic_fetch_add”

#include <iostream> 
#include <atomic> 

void add(std::atomic<double> & a, double c) 
{ 
    std::atomic_fetch_add(&a, c); 
} 

int main() 
{ 
    std::atomic<double> a; 

    a.store(0); 
    std::cout << a.load() << std::endl; 

    add(a, 5.0); 
    std::cout << a.load() << std::endl; 

    std::cin.get(); 
} 

编译它会导致:

错误LNK2019:解析外部符号“双__cdecl的std :: atomic_fetch_add( struct std :: atomic *,double)“(?? $ atomic_fetch_add @ N @ std @@ YANPAU?$ atomic @ N @ 0 @ N @ Z)在函数”void __cdecl add(struct std :: atomic &,double )“(?add @@ YAXAAU?$ atomic @ N @ std @@ N @ Z)

根据this,atomic_fetch_add定义在<atomic>,那么发生了什么?

+0

谁告诉你'std :: atomic'专门用于'double'? – Slava

+0

这是,但[没有重载需要双](http://en.cppreference.com/w/cpp/atomic/atomic_fetch_add) – Borgleader

+0

@Slava我没有看到任何我不能用它的地方'double'! – Jaber

回答

1

正如documentation说:

标准库提供的std ::原子模板的特殊化以下类型:

double不在列表中。还有非会员功能注释:

对于std :: atomic的所有成员 函数都有非成员函数模板等价物。那些非成员函数可能为 ,对于不是 std :: atomic的特化类型,但能够保证原子性的类型,也会被重载。 标准库中唯一的此类型 是std :: shared_ptr

所以double不支持。

+0

你知道任何为非整型类型实现原子算术的库吗? – Jaber

+1

@Jaber,从来不需要这样的野兽,我使用互斥 - 过早优化是万恶之源。 – Slava

+2

来澄清你的答案:'double'支持基本的原子操作,如('load','store'等);但不支持专门的操作(如算术'+','-',...),如[这里]所述(https://stackoverflow.com/questions/30048533/why-isnt-atomic-double-fully -implemented/30050429#30050429)。 – Jaber