无法将类型'T&'的非常量左值引用绑定到类型'T't ++的右值,其中std :: atomic

问题描述 投票:0回答:1

这是我的代码

#include <iostream>
#include <atomic>
using namespace std;

class T{
public:
    int i = 0;
    friend T operator++( T& t, int);
};

 T operator++( T& t, int){
        t.i++;
        return T(); // please ignore this. I only care for it to compile right now
    }



int main() {

    atomic<T> t;
    t++;
    return 0;
}

我正在尝试将原子与自定义类B一起使用,但出现错误:

*Compilation error #stdin compilation error #stdout 0s 4400KB
prog.cpp: In function ‘int main()’:
prog.cpp:21:3: error: cannot bind non-const lvalue reference of type ‘T&’ to an rvalue of type ‘T’
  t++;
   ^~
In file included from prog.cpp:2:
/usr/include/c++/8/atomic:202:7: note:   after user-defined conversion: ‘std::atomic<_Tp>::operator _Tp() const [with _Tp = T]’
       operator _Tp() const noexcept
       ^~~~~~~~
prog.cpp:11:4: note:   initializing argument 1 of ‘T operator++(T&, int)’
  T operator++( T& t, int){
    ^~~~~~~~*

我正在使用friend以避免使用显式转换

(T(t))++;

如果我用这样的const定义operator ++:

friend T operator++(const T& t, int);

它编译了,但对我当然毫无用处。

c++ operator-overloading std atomic
1个回答
0
投票

当您执行t++时,它与(t.operator T())++相同,等同于(t.operator T())++

这将返回原子持有的值的副本,该值是一个右值。增大右值是没有意义的(立即销毁),所以也许您想锁定,加载然后存储?

© www.soinside.com 2019 - 2024. All rights reserved.