From 1926e09b32fb6bd6ada6951c36cd337561964b79 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Mon, 29 Oct 2018 14:33:27 +0100 Subject: [PATCH] Warn if Q_FOREACH is used with a non-shared container Show a deprecation warning if a non shared container is used within Q_FOREACH, because it would make an expensive copy of the container Change-Id: I70cfd789b5b8d9f5b1bd6e0a57e5e968e1c6a0ca Reviewed-by: Giuseppe D'Angelo --- src/corelib/global/qglobal.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/corelib/global/qglobal.h b/src/corelib/global/qglobal.h index 1663abbf82b..d1f00234eba 100644 --- a/src/corelib/global/qglobal.h +++ b/src/corelib/global/qglobal.h @@ -1083,9 +1083,23 @@ public: int control = 1; }; +// Containers that have a detach function are considered shared, and are OK in a foreach loop +template ().detach())> +inline void warnIfContainerIsNotShared(int) {} + +#if QT_DEPRECATED_SINCE(6, 0) +// Other containers will copy themselves if used in foreach, this use is deprecated +template +QT_DEPRECATED_VERSION_X_6_0("Do not use foreach/Q_FOREACH with containers which are not implicitly shared. " + "Prefer using a range-based for loop with these containers: `for (const auto &it : container)`, " + "keeping in mind that range-based for doesn't copy the container as Q_FOREACH does") +inline void warnIfContainerIsNotShared(...) {} +#endif + template QForeachContainer::type> qMakeForeachContainer(T &&t) { + warnIfContainerIsNotShared::type>(0); return QForeachContainer::type>(std::forward(t)); }