There is a very popular question about "std::pair vs struct with two fields". But I have a question about reassigning first
and second
values to semantically named variables. In regular scenario we have something like this:
const std::pair<const int, const int> result = processSomething();
std::cout << result.second << " of " << result.first << std::endl;
But what if we assign them to reference variables first:
const std::pair<const int, const int> result = processSomething();
const int &numTotal = result.first;
const int &numSuccessful = result.second;
std::cout << numSuccessful << " of " << numTotal << std::endl;
This freeing us from writing comments about semantics of first
and second
. What disadvantages of this way? Do compilers will reserve stack for numTotal
and numSuccessful
? Will perfomance drop if this pattern used in main loop of application?
Fixes
Changed from regular variables to reference variables (thank you for comments)
const int &numTotal = pair.first;
. – Aleksei Zabrodskiistd::tie
(which assigns directly to named variables using a pair of references), which should even be faster in cases where it matters (notint
s of course). Unfortunately the language doesn't yet allow tied construction (meaning you have to first define the variables before using thetie
-trick). – Christian Rau