C++ 为什么atomic_load的参数类型是指针而不是引用?

标签 c++ c++11 stl language-lawyer

我同意 When to use references vs. pointers 中的答案.
但是,我想知道为什么 C++ 将 atomic_load 定义为

template<class T>
T atomic_load(const std::atomic<T> *obj) noexcept;
                                   ^

代替

template<class T>
T atomic_load(const std::atomic<T> &obj) noexcept;
                                   ^

谁能帮帮我?

最佳答案

我们拥有这些免费函数模板的原因是与 C11 的源代码兼容性:

#ifdef __cplusplus
#include <atomic>
#define _Atomic(X) std::atomic<X>
#else
#include <stdatomic.h>
#endif

_Atomic(int) c;

int get_c(void) { 
    return atomic_load(&c); 
}

C 没有引用。

如果您不需要它,那么 c.load() 或到 T 的隐式转换就可以正常工作。忘记免费功能曾经存在过吧。

(这也是免费函数模板的 memory_order 版本称为 atomic_load_explicit 的原因:C 中的 _Generic 支持的宏可以处理不同的参数类型,但不改变元数。)

关于C++ 为什么atomic_load的参数类型是指针而不是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46299938/

相关文章:

c++ - `template <class> friend class Foo` 是什么意思?

c++ - 有没有办法在 VSCode Mac 中链接 SFML 库?

c++ - 我可以重载具有类型特征的函数吗?

C++11 future.wait_for() 总是返回 future_status::timeout

c++ - 如何在 C++/STL 中表示键值树

c++ - 否定 remove_if 中的谓词

c++ - VC2008中返回值优化

c++ - 交替使用类作为浮点指针

c++ - 调用转换函数后是否调用了移动构造函数?

c++ - 搜索具有下限和上限的 map <pair<int, int>, ...>