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

前端 未结 4 1519
心在旅途
心在旅途 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:44

    You may use std::reference_wrapper instead of direct reference (which you cannot swap) or pointer (which may be nullptr). Something like:

    class A
    {
        std::reference_wrapper r;
    public:
       A(int& v) : r(v) {}
       void swap(A& rhs)
       {
          std::swap(r, rhs.r);
       }
    
       int& get() const { return r; }
    };
    

    Live example

提交回复
热议问题