[英]non-const in const vector
为什么 range-for over 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 向量上进行 range-for 并获取可变元素?
为什么 range-for over
const vector<Thing>
产生const Thing
?
range-for 循环使用迭代器来遍历向量。 因此,它将调用向量的begin()
方法来获取迭代器。 在const
向量上调用begin()
产生一个const_iterator
,它在取消引用时返回一个const Thing&
。
是否可以在 const 向量上进行 range-for 并获得可变元素?
不安全。 你可以const_cast
走const
从提领返回参考const_iterator
,但是这是不确定的行为,尤其是在你fn_b
实例,其中矢量的项目本身const
开始。
如果要使用可变项,则需要使用可变向量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.