为什么 std::atomic 构造函数在 C++14 和 C++17 中的行为不同

Why does std::atomic constructor behave different in C++14 and C++17

本文关键字:C++17 atomic std 构造函数 C++14 为什么      更新时间:2023-10-16

我正在一个带有 C++11 的项目,我尝试了以下代码

#include <atomic>
struct A {
std::atomic_int idx = 1;
};
int main() {
return 0;
}

我收到编译器错误

error: use of deleted function 'std::__atomic_base<_IntTp>::__atomic_base(const std::__atomic_base<_IntTp>&) [with _ITp = int]'
std::atomic_int idx = 1;
^

C++14 的结果相同。当我切换到 C++17 时,它可以工作:魔杖盒

我检查了 cpp 首选项的差异:

  • std::atomic
  • std::atomic<T>::operator=
  • std::atomic<T>::atomic

但是C++14和C++17之间没有区别。为什么它适用于 C++17 而不是 C++14?

因为在 C++17 中有一个保证的 RVO。在 C++14 中,像Foo x = Foo(args)Foo x (args)这样的语句在技术上并不相同,但它们在第 17 C++。

struct Foo {
Foo() = default;
Foo(const Foo&) = delete;
};
int main() {
// Works in C++17 and C++20, fails in C++14 and before
Foo foo = Foo(); 
}

您可以在此处阅读有关此内容的更多信息:https://en.cppreference.com/w/cpp/language/copy_elision

特别是第(since C++17)节:

T x = T(T

(f((((;//只调用一次 T 的默认构造函数, to 初始化 X

要使 C++14 代码正常工作,您可以使用

std::atomic_int idx { 1 };