Using C++11 range-based for loop correctly in Qt

后端 未结 2 638
野的像风
野的像风 2020-12-24 14:35

According to this talk there is a certain pitfall when using C++11 range base for on Qt containers. Consider:

QList list;

for(c         


        
相关标签:
2条回答
  • 2020-12-24 15:09
    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.

    This gives you:

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

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

    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;}
    

    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.

    0 讨论(0)
  • 2020-12-24 15:22

    Qt has an implementation to resolve this, qAsConst (see https://doc.qt.io/qt-5/qtglobal.html#qAsConst). The documentation says that it is Qt's version of C++17's std::as_const().

    0 讨论(0)
提交回复
热议问题