Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Why using the const keyword before and after method or function name?

I have the following code in my application. Why do we use the const keyword with the return type and after the method name?

const T& data() const { return data_; }
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
const T& data() const { return data_; }
^^^^^

means it will return a const reference to T (here data_)

Class c;
T& t = c.data()             // Not allowed.
const T& tc = c.data()      // OK.


const T& data() const { return data_; }
                ^^^^^

means the function will not modify any member variables of the class (unless the member is mutable).

void Class::data() const {
   this->data_ = ...;  // is not allowed here since data() is const (unless 'data_' is mutable)
   this->anything = ... // Not allowed unless the thing is 'mutable'
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...