Search code examples
c++c++11rvalueuniversal-reference

Whether to use T const& or T&&


I'm curious if, in general, you are to use T&& (universal reference) instead of the classic T const& (l-value reference) for templated function parameters starting with C++11. What I'm especially curious is how you get around the fact that you are forced to lose the const if you want to also handle r-value references; is there a way around this?


Solution

  • There is no problem with "losing the const". T will be deduced with cv-qualifiers if the argument is cv-qualified. For example, if the argument is an rvalue of type const std::string, then T will be deduced as const std::string. You cannot possibly violate const-correctness by using forwarding references. If you could, it would be a major language defect.

    As for the broader question of when forwarding references should be used, see here: Proper use of universal references