且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Qt 中正确使用 C++11 基于范围的 for 循环

更新时间:2021-12-06 23:12:56

template<class T>
std::remove_reference_t<T> const& as_const(T&&t){return t;}

可能会有所帮助.由于非常量迭代,返回右值的隐式共享对象可以隐式检测写入分片(和分离).

might help. An implicitly shared object returned an rvalue can implicitly detect write-shraring (and detatch) due to non-const iteration.

这给你:

for(auto&&item : as_const(foo()))
{
}

它允许您以 const 方式(而且非常清楚)进行迭代.

which lets you iterate in a const way (and pretty clearly).

如果你需要引用生命周期延长来工作,有 2 个重载:

If you need reference lifetime extension to work, have 2 overloads:

template<class T>
T const as_const(T&&t){return std::forward<T>(t);}
template<class T>
T const& as_const(T&t){return t;}

但是迭代 const 右值并关心它通常是一个设计错误:它们是丢弃的副本,为什么编辑它们很重要?如果你基于 const 限定的行为非常不同,那会在其他地方咬你.

But iterating over const rvalues and caring about it is often a design error: they are throw away copies, why does it matter if you edit them? And if you behave very differently based off const qualification, that will bite you elsewhere.