为何不能创建参考向量?

当我这样作时: ios

std::vector<int> hello;

一切正常。 可是,当我将其设为参考向量时: c++

std::vector<int &> hello;

我收到可怕的错误,例如 app

错误C2528:“指针”:指向引用的指针不合法 ui

我想将一堆对结构的引用放到一个向量中,这样我就没必要插手指针了。 为何vector对此大发脾气? 我惟一的选择是使用指针向量吗? spa


#1楼

是的,您能够寻找std::reference_wrapper ,它模仿引用但能够分配,也能够“从新放置” 指针


#2楼

Ion Todirel已经使用std::reference_wrapper提到了答案“是”从C ++ 11开始,咱们提供了一种从std::vector检索对象并使用std::remove_reference删除引用的std::remove_reference 。 下面给出了使用g++clang编译带有选项的示例
-std=c++11并成功执行。 c++11

#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";
    }             
}

#3楼

正如其余注释所建议的那样,您仅限于使用指针。 可是,若是有帮助,这是一种避免直接面对指针的技术。 code

您能够执行如下操做: 对象

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]);
}

#4楼

TL; 博士

像这样使用std::reference_wrapperrem

#include <functional>
#include <string>
#include <vector>
#include <iostream>

int main()
{
    std::string hello = "Hello, ";
    std::string world = "everyone!";
    typedef std::vector<std::reference_wrapper<std::string>> vec_t;
    vec_t vec = {hello, world};
    vec[1].get() = "world!";
    std::cout << hello << world << std::endl;
    return 0;
}

演示版

长答案

正如标准所建议的 ,对于包含类型T对象的标准容器XT必须是ErasableX Erasable

Erasable表示如下表达式格式正确:

allocator_traits<A>::destroy(m, p)

A是容器的分配器类型, m是分配器实例, p是类型*T的指针。 有关Erasable定义,请参见此处

默认状况下, std::allocator<T>用做向量的分配器。 使用默认分配器,该要求等效于p->~T()的有效性(请注意, T是引用类型,而p是指向引用的指针)。 可是, 指向引用的指针是非法的 ,所以该表达式的格式不正确。


#5楼

这是C ++语言的缺陷。 您不能使用引用的地址,由于尝试这样作会致使引用对象的地址,所以您永远没法得到指向引用的指针。 std::vector可以使用指向其元素的指针,所以须要可以存储指向的值。 您将不得不使用指针。

相关文章
相关标签/搜索