Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

c++ - Why having const and non-const accessors?

Why do the STL containers define const and non-const versions of accessors ?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because you wouldn't be able to call at on a const vector object.

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

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

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

The non-const version can be called on a non-const object and allows you to modify the returned element, which is also valid because the vector isn't 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...