[英]Does std::atomic::operator++ really return by value?
According to this prefix std::atomic<T>::operator++
returns a T
, so this code only increments v
once: 根据这个前缀,
std::atomic<T>::operator++
返回一个T
,所以这段代码只增加v
一次:
template<class T> void addTwo(std::atomic<T>& v) {
++(++v);
}
Also, std::atomic<T>::operator=
apparently returns a T
, so this code dereferences an invalid pointer that used to point to a temporary T
: 此外,
std::atomic<T>::operator=
显然返回一个T
,因此该代码取消引用一个用于指向临时T
的无效指针:
template<class T>
void setOneThenTwo(std::atomic<T>& v) {
auto ptr = &(v = 1);
*ptr = 2;
}
I am most certainly not suggesting that these code patterns are good practice, however it is highly surprising to me that std::atomic
breaks them. 我肯定不会建议这些代码模式是好的做法,但是
std::atomic
打破它们对我来说非常令人惊讶。 I always expect operator=
and prefix operator++
to return a reference to *this
. 我总是希望
operator=
和prefix operator++
返回对*this
的引用。
Question: Is cppreference right about the return types here, and if so, is there a good reason for having std::atomic
behave differently than built-in types in this regard? 问题:这里的返回类型是否正确cppreference,如果是这样,有没有一个很好的理由让
std::atomic
在这方面的行为与内置类型不同?
if operator++
returned a reference, it would have been a reference to std::atomic<T>
not to T
in which case you would need to do an additional load
to get the current value. 如果
operator++
返回了一个引用,它将是对std::atomic<T>
的引用,而不是T
在这种情况下,你需要额外load
才能得到当前值。
Imagine you've got a DBMS and you need to maintain an 'autoincrement' field 想象一下,你有一个DBMS,你需要保持一个'自动增量'字段
With operator++
retuning T
you can do this 使用
operator++
重新调整T
您可以执行此操作
class AutoIncrement
{
public:
AutoIncrement() : current (0) {}
unsigned int next()
{
return ++current;
}
private:
std::atomic<unsigned int> current;
};
Now imagine operator++
returns std::atomic<T>&
In that case when you do return ++current
it will do two things 现在假设
operator++
返回std::atomic<T>&
在这种情况下当你return ++current
它会做两件事
They are two totally independent operations. 他们是两个完全独立的行动。 If other thread calls
next
in between you will get wrong value for your autoincrement field! 如果其他线程调用
next
之间,你会得到错误的价值为您自动增量场!
According to [C++11: 29.6.5/32]
and [C++11: 29.6.5/10]
, yes, cppreference.com is correct in this regard. 根据
[C++11: 29.6.5/32]
和[C++11: 29.6.5/10]
,是的, cppreference.com在这方面是正确的。
I'm not qualified to tell you why. 我没资格告诉你原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.