Is there an elegant way to swap references in C++?

前端 未结 4 1512
心在旅途
心在旅途 2021-01-11 10:51

Sometimes classes are referencing other classes. Implementing std::swap() for such classes cannot be straightforward, because it would lead to swapping of origi

4条回答
  •  梦谈多话
    2021-01-11 11:42

    Your program using union is not legal, as you assign the reference but swap the integer than intend to use the reference again. You can read about why, here: Accessing inactive union member and undefined behavior?

    An easy solution here is to use pointers instead of references. Then everything will work smoothly, with no special code. If you really don't like this, perhaps you can use boost::optional instead of plain references, but I would struggle to see how that'd be better.

提交回复
热议问题