Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non-const in const vector

Tags:

c++

stl

Why does range-for over const vector<Thing> yield const Thing ?

I thought fn_a would compile fine :

#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();
}

Errors ( omitting some others ):

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

Q: Is it possible to range-for over a const vector and get mutable elements ?


1 Answers

Why does range-for over const vector<Thing> yield const Thing ?

A range-for loop uses an iterator to iterate through the vector. As such, it will call the vector's begin() method to get the iterator. Calling begin() on a const vector yields a const_iterator, which returns a const Thing& when dereferenced.

Is it possible to range-for over a const vector and get mutable elements ?

Not safely. You could const_cast away the const from the reference returned from dereferencing the const_iterator, but that is undefined behavior, especially in your fn_b example where the vector's items are themselves const to begin with.

If you want to work with mutable items, you need to work with a mutable vector.

like image 81
Remy Lebeau Avatar answered Apr 22 '26 19:04

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!