C ++ 20之前和之后std :: atomic的初始化 [英] Initialization of std::atomic before and after C++20
问题描述
请考虑以下两行代码:
std::atomic_flag a { }; // Since C++20
std::atomic_flag a = ATOMIC_FLAG_INIT; // Until C++20
在C ++ 20中,第一行将 a
初始化为清除状态,但是如果我在C ++ 17中使用它,则 a
将被初始化为未指定状态.第二行在C ++ 20中已弃用,但在C ++ 17中,它将 a
初始化为clear状态.如何在代码中同时包含它们?我想我应该使用一个宏,但是那个宏到底是什么?并能用于所有其他 std :: atomic< T>
类型的初始化吗?
In C++20, the first line initializes a
to the clear state, but if I use that in C++17, a
will be initialized to an unspecified state. The second line is deprecated in C++20, but in C++ 17, it initializes a
to the clear state. How can I have them both in a code? I guess I should use a macro, but what is that macro exactly? And does it work for the initialization of all the other std::atomic<T>
types?
推荐答案
基于@chris注释,我认为以下代码可以完成这项工作:
Based on @chris comment, I think the following code will do the job:
#if __has_cpp_attribute(__cpp_lib_atomic_value_initialization)
std::atomic_flag a { };
#else
std::atomic_flag a = ATOMIC_FLAG_INIT;
#endif
所需的宏在< memory>
,< atomic>
和< version>
头文件之一中定义.我当然不想写已经被弃用的东西(即允许使用,但由于某些原因而劝阻).
The required macros are defined in either one of <memory>
, <atomic>
, and <version>
header files. I certainly don't want to write something that is already deprecated (ie, the use is allowed, but discouraged for some reason).
这篇关于C ++ 20之前和之后std :: atomic的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!