[英]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.