Why can't I make a vector of references?

前端 未结 9 605
梦如初夏
梦如初夏 2020-11-22 03:32

When I do this:

std::vector hello;

Everything works great. However, when I make it a vector of references instead:



        
相关标签:
9条回答
  • 2020-11-22 04:13

    yes you can, look for std::reference_wrapper, that mimics a reference but is assignable and also can be "reseated"

    0 讨论(0)
  • 2020-11-22 04:14

    As the other comments suggest, you are confined to using pointers. But if it helps, here is one technique to avoid facing directly with pointers.

    You can do something like the following:

    vector<int*> iarray;
    int default_item = 0; // for handling out-of-range exception
    
    int& get_item_as_ref(unsigned int idx) {
       // handling out-of-range exception
       if(idx >= iarray.size()) 
          return default_item;
       return reinterpret_cast<int&>(*iarray[idx]);
    }
    
    0 讨论(0)
  • 2020-11-22 04:21

    Ion Todirel already mentioned an answer YES using std::reference_wrapper. Since C++11 we have a mechanism to retrieve object from std::vector and remove the reference by using std::remove_reference. Below is given an example compiled using g++ and clang with option
    -std=c++11 and executed successfully.

    #include <iostream>
    #include <vector>
    #include<functional>
    
    class MyClass {
    public:
        void func() {
            std::cout << "I am func \n";
        }
    
        MyClass(int y) : x(y) {}
    
        int getval()
        {
            return x;
        }
    
    private: 
            int x;
    };
    
    int main() {
        std::vector<std::reference_wrapper<MyClass>> vec;
    
        MyClass obj1(2);
        MyClass obj2(3);
    
        MyClass& obj_ref1 = std::ref(obj1);
        MyClass& obj_ref2 = obj2;
    
        vec.push_back(obj_ref1);
        vec.push_back(obj_ref2);
    
        for (auto obj3 : vec)
        {
            std::remove_reference<MyClass&>::type(obj3).func();      
            std::cout << std::remove_reference<MyClass&>::type(obj3).getval() << "\n";
        }             
    }
    
    0 讨论(0)
提交回复
热议问题