Is the reuse of a pair of links similar to this legal?

I want to move a pair of refPair links

 int a, b, c, d; pair<int&, int&> refPair(a, b); 

Doing this seems to copy the values โ€‹โ€‹of c and d to copy to and b, which I don't want

 refPair = pair<int&, int&>(c, d); 

Doing this, however, does not

 new(&refPair) pair<int&, int&>(c, d); 

I want to know if this is legal and does not cause any undefined behavior. It works great with my compiler, but I'm not sure if its portable.

+4
source share
2 answers

I am sure that this behavior is undefined, since it is illegal to build on non-trivial classes (std :: pair can be non-trivial AFAIK).

In any case, take a look at std::reference_wrapper , which can be reinstalled.

 refPair = pair<std::reference_wrapper<int>, std::reference_wrapper<int> >(std::ref(c), std::ref(d)); 
+4
source

You write,

"want to reinstall refPair link pair"

No, links cannot be restored.

Technically, you could use pointers instead.

But what your original code does does not make sense. And the fact that your corrected "working" code makes senseless and formally unproductive. Therefore, there is a possibility that this is a question of XY, that is, where do you ask about the shortcomings of an imaginary solution Y instead of the real problem X - what is there?

0
source

All Articles