How can I change the variable to which a C++ reference refers?

前端 未结 10 1040
既然无缘
既然无缘 2020-11-29 01:50

If I have this:

int a = 2;
int b = 4;
int &ref = a;

How can I make ref refer to b after this code?

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 02:11

    With C++11 there is the new(ish) std::reference_wrapper.

    #include 
    
    int main() {
      int a = 2;
      int b = 4;
      auto ref = std::ref(a);
      //std::reference_wrapper ref = std::ref(a); <- Or with the type specified
      ref = std::ref(b);
    }
    

    This is also useful for storing references in containers.

提交回复
热议问题