In C++, what’s the difference in behavior between std::pair<const T, const U> and const std::pair<T, U>?
In C++, what’s the difference in behavior between std::pair<const T, const U> and const
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The core difference is that they are different unrelated types (with some implicit conversions among them).
While there are implicit conversions that allow
f(pc)to compile, that line involves a conversion, and the conversion involves making a copy of thelongstring()s. On the other hand, the callf(cp)only binds a constant reference to the existing pair as the type matches, not requiring any copies.The fact that the compiler let’s you write similar code, does not mean that the code is compiled to do the same thing. This is particularly true for types with implicit conversions, as is the case of
std::pairThis is a common pitfall when writing functors to operate on elements stored in maps, where a mismatch on the argument of the functor will cause unnecessary copying of the object data:
The lambda above does not have the correct type of argument (
std::pair<int,std::stringvs.std::pair<const int,std::string>) and that causes each call to copy both the index and the value (i.e. all strings will be copied, to anstd::pair<int,std::string>and then a reference bound for the argument to the lambda). The simple recommendation in this case would be to usestd::map<int,std::string>::value_type const &for the argument type.