std::atomic error: no ‘operator++(int)’ declared for postfix ‘++’ [-fpermissive]

std::atomic error: no ‘operator++(int)’ declared for postfix ‘++’ [-fpermissive]

我试图通过不同的线程更新一个 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)) ;
    }
}

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

error: no ‘operator++(int)’ declared for postfix ‘++’ [-fpermissive]

fn_write()声明为const成员函数,其中done数据成员不可修改

根据您的意图,您可以使 fn_write() 成为非常量:

bool fn_write (int size) {
    ... ...
}

或者,您可以将 done 设为 mutable:

mutable std::atomic<int> done;

bool fn_write (int size) const {
    ... ...
}