c++ std::atomic<bool>::fetch_or not implemented?

橙三吉。 提交于 2019-12-12 16:19:52

问题


With this excerpt of code:

class myclass {
    volatile std::atomic<bool> flag;
    public:
    myclass(): flag(false) {}
    bool get_flag() { return flag; }
    bool try_set() {
        return !flag.fetch_or(flag, true);
    }
    void reset() {
        flag = false;
    }
};

I am having this compile error:

error: ‘volatile struct std::atomic<bool>’ has no member named ‘fetch_or’   
   return !flag.fetch_or(flag, true);

It compiles if, however, I change the template parameter to int:

class myclass {
    volatile std::atomic<int> flag;
    public:
    myclass(): flag(0) {}
    bool get_flag() { return flag; }
    bool try_set() {
        return !flag.fetch_or(flag, true);
    }
    void reset() {
        flag = 0;
    }
};

The atomic reference says that "the full specialization atomic<bool>" is treated as "non-specialized", what I believe to be the source of the problems. So my doubts:

  1. How can a "full specialization" be "treated as non-specialized"?
  2. May there I face any tricky pitfalls using as flag template parameter int instead of bool when calling flag.fetch_or()?

I am using gcc 5.1.0, and compiling with -std=c++14.


回答1:


The C++11 N3337 draft does not require that method for bool.

29.5 "Atomic types"

template <class T> struct atomic {
  [...]
}

template <> struct atomic<integral> {
  [...]
  integral fetch_or(integral , memory_order = memory_order_seq_cst) noexcept;
  [...]
}

29.5/1:

The semantics of the operations on specializations of atomic are defined in 29.6.

29.6.3/2 "Arithmetic operations on atomic types":

In the declarations of these functions and function template specializations, the name integral refers to an integral type and the name atomic-integral refers to either atomic or to a named base class for integral from Table 145 or inferred from Table 146.

and Table 145 does not contain bool.

So only the integral (without bool) specializations of struct will have that method.

This is a bit confusing because in the rest of the standard, "integral types" includes bool, 3.9.1/7 "Fundamental types":

Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types. A synonym for integral type is integer type.



来源:https://stackoverflow.com/questions/30254582/c-stdatomicboolfetch-or-not-implemented

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!