std :: atomic错误:没有为后缀'++'声明'operator ++(int)'[-fpermissive]

Tus*_*har 3 c++ const c++11 stdatomic

我试图atomic通过不同的线程更新变量,并得到此错误。这是我的代码。

class counter {
    public:
    std::atomic<int> done;

    bool fn_write (int size) const {
        static int count = 0;
        if (count == size) {
            done++;
            count = 0;
            return false;
        } else {
            count++;
            return true;
        }
    }
};

int main() {
    counter c1;
    for (int i=0; i<50; i++) {
        while (! c1.fn_write(10)) ;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在第8行中遇到以下错误done++

错误:没有为后缀'++'声明'operator ++(int)'[-fpermissive]

son*_*yao 5

fn_write()被声明为const成员函数,在该成员函数done中不能修改数据成员。

根据您的意图,可以将fn_write()其设为非常量:

bool fn_write (int size) {
    ... ...
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使done成为mutable

mutable std::atomic<int> done;

bool fn_write (int size) const {
    ... ...
}
Run Code Online (Sandbox Code Playgroud)