Reputation: 41
So once an std::pair
with at least one reference variable has been initialized, for example like this:
int a = 53;
int b = 42;
std::pair<int, int&> foo(33, a);
Is there a way to change where the reference variable is pointing?
Assignment:
foo = std::make_pair(33, std::ref(b));
and swapping:
std::pair<int, int&> bar(33, b);
foo.swap(bar);
appear to just move the new contents to a
and leave second member of foo
pointing where it was before (a
), therefore not doing what I'm trying to achieve here. I am aware that references cannot be rebound as
answered here, but this isn't what I am trying to do here. What I'm trying to do is make a new pair and assign its contents to an existing one which technically isn't the same thing.
Thanks in advance!
Upvotes: 3
Views: 231
Reputation: 118445
References always work the same way in C++.
int a;
int &b=a;
b
will always be a reference to a
, until b
goes out of scope and gets destroyed.
References in std::pair
s, or anywhere else, work the same way. Once they are bound, they will always refer to the same object they were bound to. Assigning to a reference will always assign to the referenced object.
It also doesn't matter what the reference is to, to an int
, to a char
, or to any other objects. References always work the same way, in this respect.
Upvotes: 5
Reputation: 21160
...but you kinda can. Trying to assign a reference is impossible, but you can achieve the same effect
new (&foo) std::pair<int, int&>(33, b);
will destroy the old pair† and construct a new pair referencing b
. You are correct, a pair with a reference member isn't the same as a plain reference.
There are many rules, caveats and ways you can make a mistake here. Just accept that references aren't meant for reassignment.
†But not call the destructor, which is fine here. Placement new is less error prone in C++20 due to this.
Upvotes: 1
Reputation: 238401
What I'm trying to do is make a new pair and assign its contents to an existing one which technically isn't the same thing.
You can do that. The assignment operator of the pair assigns each member. When a reference member is assigned, the referred object is assigned. If you want this assignment to rebind the member of that pair, then you want what you know is not possible.
Upvotes: 0