Std :: pair, assigning the first and second semantically named variables

There is a very popular question about "std :: pair vs struct with two fields". But I have a question about the reassignment of values firstand secondto semantically named variables. In the normal 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 first assign them reference variables:

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 frees us from writing comments about semantics firstand second. What are the disadvantages of this path? Can compilers reserve a stack for numTotaland numSuccessful? Will performance be canceled if this pattern is used in the main application loop?

difficult

Changed from regular variables to reference variables (thanks for the comments)

+3
1

, . , , , , , (, const- ).

: pair , pair :

int numTotal;
int NumSuccessful;
std::pair<int&, int&> result(numTotal, numSuccessful);
result = processSomething();

, :

int numTotal;
int NumSuccessful;
std::pair<int&, int&>(numTotal, numSuccessful) = processSomething();

++ 11 tie:

int numTotal;
int NumSuccessful;
std::tie(numTotal, numSuccessful) = processSomething();

const, :

struct Num {
  Num(std::pair<const int, const int> p) : total(p.first), successful(p.second) { }
  int total;
  int sucessful;
};
const Num num = processSomething();
std::cout << num.successful << '/' << num.total << '\n';
+8

All Articles