Dappur
Dappur

Reputation: 69

Why do implicitly-generated deduction guides result in different behavior of the structured binding declaration?

This is the minimal reproduction code:

#include <cstdio>
#include <utility>
#include <type_traits>
using std::pair;

template<typename T>
inline constexpr bool check_v = std::is_rvalue_reference_v<T>;

template<class T>
void f(T &&p){
    auto [x,y] = std::pair<int,int>(p);  // <--- line 11; the program outputs 1 1
    //auto [x,y] = std::pair(p);         // <--- line 12; the program outputs 0 0
    printf("%d %d\n", check_v<decltype(x)>, check_v<decltype(y)>);
}

int main()
{
    pair p{0,0};
    f(p);
    return 0;
}

The program outputs different results if switching between line 11 and 12. The code was compiled in C++17 standard (-std=c++17) across multiple g++ versions from 10.1 to 13.2 but they all gave the same results.

I thought the line 11 and 12 have the same meaning. The only difference I could say was that line 12 additionally invokes a implicitly-generated deduction guides to pair(const pair&), and the generated assembly code (using -S flag) confirms that they invoks the same constructor.

I was expecting the two lines had the same effect so I wonder the reason about the different outputs, and which one is what we "expect"? Thanks in advance for any answers/discussions!

Upvotes: 5

Views: 61

Answers (1)

user17732522
user17732522

Reputation: 76859

Looks like a GCC bug to me. It should result in 0 0 in both cases and does behave this way on Clang.

There is already a bug report here.

Upvotes: 4

Related Questions