const向量中的非const

时间:2018-02-14 04:48:54

标签: c++ stl

为什么范围超过const vector<Thing>会产生const Thing

我认为fn_a可以正常编译:

#include <vector>

class Some {
    public:
      void not_const();
};


void fn_a ( const std::vector<Some> &vs) {
     for( Some &s : vs )
        s.not_const();

}

void fn_b (  std::vector<Some const> &vs) {
     for( Some &s : vs )
        s.not_const();
}

错误(省略其他错误):

a.cc:10:21: error: binding reference of type ‘Some&’ to ‘const Some’ discards qualifiers
a.cc:16:21: error: binding reference of type ‘Some&’ to ‘const Some’ discards qualifiers

问:是否可以在const矢量范围内获得可变元素?

1 个答案:

答案 0 :(得分:2)

  

为什么范围超过const vector<Thing>会产生const Thing

range-for循环使用迭代器迭代向量。因此,它将调用向量的begin()方法来获取迭代器。在begin()向量上调用const会产生const_iterator,在取消引用时会返回const Thing&

  

是否可以在const矢量范围内获得可变元素?

不安全。您可以const_cast离开const取消引用的引用中的const_iterator,但这是未定义的行为,尤其是在fn_b示例中,向量的项目本身就是const 1}}开头。

如果您想使用可变项,则需要使用可变向量。