On Friday 20 February 2015 02:26:25 Thiago Macieira wrote:
> Do NOT do this. This will crash:
> 
>         for (auto const &item : std::cref(somefunction()) { ... }

Sorry for warming up an old thread, but since there was talk about the QtC 
coding style recommending this...

It's safe for lvalues. What't not safe are rvalues, but the std:.cref() 
overload from rvalues (const) is supposed to be deleted, according o en-
cppreference.com, so it shouldn't even compile. Doesn't help much if the 
compiler doesn't know = delete, though.

This might work, based on the cref() overload pattern:

      template <typename T>
      class QContainerWrapper {
          T container;
          friend decltype(auto) begin(const QContainerWrapper &w)
              Q_DECL_NOEXCEPT_EXPR(noexcept(w.container.begin()))
          { return w.container.begin(); }
          friend decltype(auto) end(const QContainerWrapper &w)
              Q_DECL_NOEXCEPT_EXPR(noexcept(w.container.end()))
          { return w.container.end(); }
      };
      // assume the following are friends of QContainerWrapper<T/T&>, resp.:
      template <typename T>
      QContainerWrapper<T&> qAsConst(const T &t) // lvalue
          Q_DECL_NOTHROW
      { return {t}; } // stores reference
      template <typename T>
      QContainerWrapper<T> qAsConst(const T &&t)
          Q_DECL_NOEXCEPT_EXPR(std::is_nothrow_move_constructible_v<T>)
      { return {std::move(t)}; } // stores a copy

Untested!

Thanks,
Marc

-- 
Marc Mutz <marc.m...@kdab.com> | Senior Software Engineer
KDAB (Deutschland) GmbH & Co.KG, a KDAB Group Company
Tel: +49-30-521325470
KDAB - The Qt Experts
_______________________________________________
Development mailing list
Development@qt-project.org
http://lists.qt-project.org/mailman/listinfo/development

Reply via email to