1

I am not going to do something like this in real code, just want to better understand std::make_pair(). I have read cppreference, but I don't understand std::decay well. I find this to be a bit confusing:

std::vector<std::pair<int*, int*>> vec;
int* a = new int(1);
int* b = new int(2);
vec.emplace_back(std::make_pair(a, b)); // Fine
vec.emplace_back(std::make_pair<int*, int*>(&*a, &*b)); // Fine
vec.emplace_back(std::make_pair<int*, int*>(a, b)); // Error

Why do the first two calls to std::make_pair() work, but the last one gives an error?

GCC: cannot bind rvalue reference of type ‘int*&&’ to lvalue of type ‘int*’
Clang: no matching function for call to 'make_pair'

How does the last std::make_pair() differ from the previous two?

Sneftel
  • 40,271
  • 12
  • 71
  • 104
Alexey104
  • 969
  • 1
  • 5
  • 17
  • 1
    `a` and `b` are lvalues while `&*a` and `&*b` are rvalues and rvalue reference can't bind to an lvalue so the third example doesn't work. Note that you're explicitly providing the template arguments in your examples so type deduction doesn't happen here. – Jason Aug 16 '22 at 12:15
  • 2
    fwiw, you do not need `make_pair` here. Just do `vec.emplace_back(a,b);` – 463035818_is_not_an_ai Aug 16 '22 at 12:24
  • 3
    Note that only the first example is doing type deduction. The second and third examples are not deducing anything, so the answer to "How does type deduction work?" is "It doesn't. You disabled it." I think you are confusing the template type parameters to `make_pair`. They are not the types of the pair you want to make. They describe the types of the things you are making a pair *from*. – Raymond Chen Aug 16 '22 at 12:32

0 Answers0