简体   繁体   English

std :: vector元素中的const引用

[英]Const references in std::vector elements

Is it only my compiler or is it forbidden to use cons references in std::vector elements. 它只是我的编译器还是禁止在std :: vector元素中使用cons引用。 Consider following structure: 考虑以下结构:

struct Y
{
  const int & x;

  Y(const int & p_x):
        x(p_x)
  {
  }
};

Now, when I try to push such object onto vector: 现在,当我尝试将这样的对象推送到vector时:

std::vector<Y> yv;
int x = 5;
Y y(x);
yv.push_back(y);

I get compiler error: "error: non-static reference member `const int&Y::x', can't use default assignment operator". 我得到编译器错误:“错误:非静态引用成员`const int&Y :: x',不能使用默认赋值运算符”。 Shouldn't copy ctor be enough? 不应该复制ctor就够了吗?

The vector elements must be assignable. vector元素必须是可分配的。 From section 23.2.4 Class template vector of the C++ standard: 从第23.2.4节C ++标准的类模板向量

...the stored object shall meet the requirements of Assignable. ......存储的对象应满足Assignable的要求。

You may want to check 你可能想检查一下

std::reference_wrapper

available with C++11 适用于C ++ 11

No, because you can't assign to a const reference and the STL containers make use of assignment for moving items around. 不,因为您无法分配给const引用,并且STL容器使用赋值来移动项目。

You're better using a shared_ptr ( boost:: or std:: depending on your environment) or a raw pointer. 你最好使用shared_ptrboost::std::取决于你的环境)或原始指针。

An assignment operator is necessary because vector default constructs elements in extra slots ahead of time. 赋值运算符是必需的,因为vector默认值会提前在额外的时隙中构造元素。

Later, instead of reallocating, it uses the assignment operator to assign those default instances to whatever you push into the vector. 稍后,它不使用重新分配,而是使用赋值运算符将这些默认实例分配给您向量中推送的任何内容。

It is generally forbidden to use references in any container. 通常禁止在任何容器中使用引用。 You can justify this by the fact, that a vector for example allocates the data in forehand and references can just be assigned once (during initialization). 您可以通过以下事实来证明这一点:例如,向量分配正手中的数据,而引用只能分配一次(在初始化期间)。

I finally used 我终于用过了

 std::vector< const Type* >

Not the best looking, but it does the same job. 不是最好看的,但它做同样的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM