具有原子成员的类的复制构造函数 [英] Copy constructor for classes with atomic member

查看:34
本文介绍了具有原子成员的类的复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有原子成员的类,我想编写一个复制构造函数:

I have a class with an atomic member and i want to write a copy constructor:

struct Foo
{
    std::atomic<int> mInt;

    Foo() {}
    Foo(const Foo& pOther)
    {
        std::atomic_store(mInt, std::atomic_load(pOther.mInt, memory_order_relaxed), memory_order_relaxed);
    }
};

但我不知道我必须使用哪个顺序,因为我不知道这个复制构造函数将在何时何地被调用.

But i don't know which ordering i must use, because i don't know where and when this copy constructor will be called.

我可以对复制构造函数和赋值运算符使用 relaxed 排序吗?

Can i use relaxed ordering for copy constructor and assignment operator?

推荐答案

不,如果你不知道它将如何使用,你应该使用 memory_order_seq_cst 以确保安全.如果您使用 memory_order_relaxed,您可能会遇到指令重新排序的问题.

No, if you don't know how it will be used, you should use memory_order_seq_cst to be safe. If you use memory_order_relaxed, you could run into issues with instructions being reordered.

这篇关于具有原子成员的类的复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆