Il 20/10/18 14:43, Elvis Stansvik ha scritto:
In our application we added a helper like

template <typename T>
const T moveToConst(T &&t)
{
     return std::move(t);
}

that we use for these cases. It just moves the argument to a const
value and returns it. With that we can do for (auto foo :
moveToConst(returnsQtContainer()) { ... }.

Since it's such a common pattern to want to iterate a returned Qt
container, what would you think of having such a helper
(qMoveToConst?) in Qt?

Possibly... Note however that such a thing was already proposed for qAsConst itself, and shut down to avoid having qAsConst diverge from std::as_const (and I approve of not having Qt-specific behaviours). I can't find the relevant discussion on the mailing list right now.


For reference, std::as_const's original authors had doubts about the lifetime issues around this, saying that more investigations were needed:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0007r0.html#9.0


After a LEWG meeting it was reworded like this:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0007r1.html#8.0


I'm not entirely sure of what prompted the change for as_const -- if just a safety net while waiting for more investigation, or if something more profound was raised.


I can easily imagine however a scenario where moveToConst() can lead to worse code than the current solution.

Current solution:

// GCE may get applied, 0 moves
const QVector<Object> v = getVector();
for (auto &obj : v) ~~~

vs.

// Always 2 moves
for (auto &obj : qMoveToConst(getVector()) ~~~


And if the type is not even cheap to move (e.g. QVLA, std::array), qMoveToConst becomes a really unpleasant surprise.

How about asking LEWG about their reasoning too?


My 2 c,
--
Giuseppe D'Angelo | [email protected] | Senior Software Engineer
KDAB (France) S.A.S., a KDAB Group company
Tel. France +33 (0)4 90 84 08 53, http://www.kdab.com
KDAB - The Qt, C++ and OpenGL Experts

Attachment: smime.p7s
Description: Firma crittografica S/MIME

_______________________________________________
Development mailing list
[email protected]
http://lists.qt-project.org/mailman/listinfo/development

Reply via email to