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

后端 未结 2 654
野的像风
野的像风 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条回答
  •  萌比男神i
    2020-12-24 15:09

    template
    std::remove_reference_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
    T const as_const(T&&t){return std::forward(t);}
    template
    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.

提交回复
热议问题