c++ - 带有自定义类的 std::atomic (C++ 11)

标签 c++ xcode c++11 atomic

我在我的库中使用带有自定义类的 std::atomic。 MSVC 一切正常,但现在我试图让它在 macOS 上运行,我得到一个链接器错误:

架构 x86_64 的 undefined symbol : “__atomic_store”,引用自: _main in main.o

我创建了一些测试代码来复制它

#include <iostream>
#include <atomic>

using namespace std;

class Vec {
    public:
    int x, y, z;
    Vec() { x = y = z = 0; }
};

std::atomic<Vec> x;


int main()
{
  Vec a;
  x = a;
  cin.get();
    return 0;
}

当然这个例子没有多大意义,但它是我能想到的最短的例子。它确实在 VS2012 中运行,但不在 xcode 中(给我上面显示的链接器错误)。

那么发生了什么?我在这里滥用 std::atomic 吗?我正在研究的库是大量多线程的,用于音频处理。因此,如果我没有以正确的方式使用 std::atomic,它并没有真正显示出来,因为性能非常好,而且我没有任何线程问题。还是 xcode 可能缺少什么?

更新:

我检查了安德烈的答案,因为它包含最多的信息,尽管所有 3 个答案都很有用。我不是这方面的专家(显然),但似乎 VS2012 超出了应该在 C++11 中实现的范围。

那么从这里怎么走?我看到了一些选项。

  1. 不要对此类使用原子。在我的特殊情况下,这将非常困难,因为我的 vector 类在整个代码中都使用了。锁定和解锁互斥锁可能会大大减慢速度。
  2. 自己实现原子功能。这对我来说看起来很复杂。我会将其保存为最后一个选项。
  3. 看看是否可以用 boost::atomic 做点什么。乍一看,这似乎有效。不过,我必须对其进行更多测试。

最佳答案

http://en.cppreference.com/w/cpp/atomic/atomic 中所述:

The standard library provides full specializations of the std::atomic template for the following types:

1) One specialization for the type bool and its typedef
2) Specializations and typedefs for integral types
3) std::atomic for all pointer types

Boost.Atomic 怎么样。如 Boost.Atomic limitations 中所述:

Using non-POD-classes as template parameter to atomic results in undefined behavior.

关于c++ - 带有自定义类的 std::atomic (C++ 11),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15886308/

相关文章:

algorithm - "find the line that contains the maximum number of points in P"的哈希函数

c++ - 为什么在这种情况下 cout 不会溢出?

c++ 以此类为类型继承类模板

c++ - Windows XP 在启动时用 C++ 读取文本文件的速度较慢;预取?

c++ - 如果输出无关紧要,则不会调用函数

xcode - 无法在 OS X 中加载内核扩展(.kext 文件)(不包含架构 :x86_64 error) 的代码)

ios - 我如何检测在文本字段的键盘上按下了哪个键?

c++ - 在 C++ 中将日期转换为 unix 时间戳

ios - Xcode 在将其添加到 Storyboard后更改对象类

c++ - 在 C++11 的 lambda 中使用封闭函数中的模板类型可以吗?