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

constants - C++ Const Usage Explanation

const int* const Method3(const int* const&) const;

Can someone explain the usage of each of the const?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

It's easier to understand if you rewrite that as the completely equivalent

// v───v───v───v───v───v───v───v───v───v───v───v─┬┐
//                                               ││
//  v──#1    v─#2             v──#3    v─#4      #5
   int const * const Method3(int const * const&) const;

then read it from right to left.

#5 says that the entire function declaration to the left is const, which implies that this is necessarily a member function rather than a free function.

#4 says that the pointer to the left is const (may not be changed to point to a different address).

#3 says that the int to the left is const (may not be changed to have a different value).

#2 says that the pointer to the left is const.

#1 says that the int to the left is const.

Putting it all together, you can read this as a const member function named Method3 that takes a reference to a const pointer to an int const (or a const int, if you prefer) and returns a const pointer to an int const (const int).

(N.b. #2 is entirely superfluous.)


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

...