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
247 views
in Technique[技术] by (71.8m points)

c++ - What's the difference between a const member function and a non-const member function?

I am very confused about the const version and non-const version member function like below:

value_type& top() { return this.item }
const value_type& top() const { return this.item }

What is the difference between these two functions? In what situation would they be used?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In short, they're used to add 'const correctness' to your program.

value_type& top() { return this.item }

This is used to provide mutable access to item. It is used so you can modify the element in the container.

For example:

c.top().set_property(5);  // OK - sets a property of 'item'
cout << c.top().get_property();  // OK - gets a property of 'item'

One common example for this pattern is returning mutable access to an element with vector::operator[int index].

std::vector<int> v(5);
v[0] = 1;  // Returns operator[] returns int&.

On the other hand:

const value_type& top() const { return this.item }

This is used to provide const access to item. It's more restrictive than the previous version - but it has one advantage - you can call it on a const object.

void Foo(const Container &c) {
   c.top();  // Since 'c' is const, you cannot modify it... so the const top is called.
   c.top().set_property(5);  // compile error can't modify const 'item'.
   c.top().get_property();   // OK, const access on 'item'. 
}

To follow the vector example:

const std::vector<int> v(5, 2);
v[0] = 5;  // compile error, can't mutate a const vector.
std::cout << v[1];  // OK, const access to the vector.

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

...