gpt4 book ai didi

C++0x |为什么 std::atomic 使用 volatile-qualifier 重载每个方法?

转载 作者:可可西里 更新时间:2023-11-01 18:38:47 25 4
gpt4 key购买 nike

当前草案的以下摘录说明了我的意思:

namespace std {
typedef struct atomic_bool {
bool is_lock_free() const volatile;
bool is_lock_free() const;
void store(bool, memory_order = memory_order_seq_cst) volatile;
void store(bool, memory_order = memory_order_seq_cst);
bool load(memory_order = memory_order_seq_cst) const volatile;
bool load(memory_order = memory_order_seq_cst) const;
operator bool() const volatile;
operator bool() const;
bool exchange(bool, memory_order = memory_order_seq_cst) volatile;
bool exchange(bool, memory_order = memory_order_seq_cst);
bool compare_exchange_weak(bool&, bool, memory_order, memory_order) volatile;
bool compare_exchange_weak(bool&, bool, memory_order, memory_order);
bool compare_exchange_strong(bool&, bool, memory_order, memory_order) volatile;
bool compare_exchange_strong(bool&, bool, memory_order, memory_order);
bool compare_exchange_weak(bool&, bool, memory_order = memory_order_seq_cst) volatile;
bool compare_exchange_weak(bool&, bool, memory_order = memory_order_seq_cst);
bool compare_exchange_strong(bool&, bool, memory_order = memory_order_seq_cst) volatile;
bool compare_exchange_strong(bool&, bool, memory_order = memory_order_seq_cst);
atomic_bool() = default;
constexpr atomic_bool(bool);
atomic_bool(const atomic_bool&) = delete;
atomic_bool& operator=(const atomic_bool&) = delete;
atomic_bool& operator=(const atomic_bool&) volatile = delete;
bool operator=(bool) volatile;
} atomic_bool;
}

Volatile 具有传递性。因此,您不能从 volatile 对象调用非 volatile 成员函数。另一方面,允许从非 volatile 对象调用 volatile 成员函数。

那么,原子类中的volatile和non-volatile成员函数在实现上有什么区别吗?换句话说,是否需要非 volatile 重载?

最佳答案

我认为 volatile 重载的存在是出于效率原因。在 C++0x 中, volatile 读取和写入本质上比非 volatile 读取和写入更昂贵,因为内存模型提出了一些严格的要求,以防止缓存 volatile 变量的值。如果所有函数都只标记为 volatile,那么代码不一定会进行某些优化以提高性能。有了这种区别,编译器就可以在可能的情况下优化非 volatile 读取和写入,同时在需要 volatile 读取和写入时优雅地降级。

关于C++0x |为什么 std::atomic 使用 volatile-qualifier 重载每个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4870869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com