Why MSVC compile a structured binding of `std::pair` worse in `/std:c++20` than in `/std:c++latest` With Example?

Structured binding of std::pair generates slower code in MSVC /std:c++20 than /std:c++latest. Learn why, and the best fixes: direct member access or const auto& reference binding.

Solution 1 (Recommended): Direct member access

float bindPair(std::pair<int, float>* s, int i) {
   return s[i].first + s[i].second;
}

This completely sidesteps the issue. No temporary std::pair is created, no stack spill, no reload — the compiler reads both members straight from memory. This works identically on MSVC, GCC, and Clang, regardless of standard mode.

Solution 2: Reference binding instead of value binding

If you want to keep the structured binding syntax for readability:

float bindPair(std::pair<int, float>* s, int i) {
   const auto& [a, b] = s[i];
   return a + b;
}

const auto& binds a and b as references into s[i], avoiding the copy of the pair object. (Value binding const auto [a, b] = ... is what creates the temporary that MSVC mishandles in C++20 mode.)

Solution 3: Compile with /std:c++latest

If your project can move to C++23 mode, the language rules for std::pair construction change (P2321R2 adds a converting constructor), and MSVC is optimizer handles the structured binding case well there.

Example

#include <utility>

// Slow on MSVC /std:c++20 — hidden pair copy → stack temporary → reload
float bad(std::pair<int, float>* s, int i) {
   const auto [a, b] = s[i];
   return a + b;
}

// Best: no copy at all, portable across compilers
float good1(std::pair<int, float>* s, int i) {
   return s[i].first + s[i].second;
}

// Good alternative: reference binding, no copy
float good2(std::pair<int, float>* s, int i) {
   const auto& [a, b] = s[i];
   return a + b;
}

Why this matters?

In a hot loop, the C++20 value-binding version forces the 8-byte pair through a stack temporary, breaking store-to-load forwarding and costing roughly 15% throughput. Direct member access (Solution 1) is the safest, compiler independent fix it has zero dependence on optimizer behavior and is equally fast everywhere.

9 Views