Why do we need const and non-const constructors?

Why do STL containers define constant and non-content versions of accessories?

What is the advantage of defining const T& at(unsigned int i) const and T& at(unsigned int) , and not just the non-constant version?

+4
source share
1 answer

Because you cannot call at in a const vector object.

If you had a non- const version, the following:

 const std::vector<int> x(10); x.at(0); 

will not compile. Having a const version makes this possible and, at the same time, prevents you from actually changing what at returns - this is a contract, since the vector is const .

The non const version can be called not by the const object and allows you to change the returned element, which is also valid because the vector is not const.

 const std::vector<int> x(10); std::vector<int> y(10); int z = x.at(0); //calls const version - is valid x.at(0) = 10; //calls const version, returns const reference, invalid z = y.at(0); //calls non-const version - is valid y.at(0) = 10; //calls non-const version, returns non-const reference //is valid 
+8
source

Source: https://habr.com/ru/post/1447304/


All Articles