gpt4 book ai didi

c++ std::atomic::fetch_or 未实现?

转载 作者:太空狗 更新时间:2023-10-29 21:18:26 25 4
gpt4 key购买 nike

使用这段代码摘录:

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;
}
};

我有这个编译错误:

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

但是,如果我将模板参数更改为 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;
}
};

atomic引用资料说“完全特化 atomic<bool> ”被视为“非特化”,我认为这是问题的根源。所以我的疑问:

  1. “完全特化”如何被“视为非特化”?
  2. 在使用 as 标志模板参数 int 时,我是否会遇到任何棘手的陷阱?而不是 bool打电话时 flag.fetch_or()

我正在使用 gcc 5.1.0,并使用 -std=c++14 进行编译.

最佳答案

C++11 N3337 draft bool 不需要该方法。

29.5 “原子类型”

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 “原子类型的算术运算”:

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.

并且表 145 不包含 bool

因此只有 struct 的积​​分特化(没有 bool)才有那个方法。

这有点令人困惑,因为在标准的其余部分,“整数类型”包括 bool,3.9.1/7“基本类型”:

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.

关于c++ std::atomic<bool>::fetch_or 未实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30254582/

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