What else does "Const" do in C ++ and then tells the compiler that the particular thing is read-only

Well, I didn't get it, what const

can be as confusing as pointers. Could someone please explain in order what exactly the following code does in terms const

?

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

      

It's so confusing even for a non-beginner programmer.

+3


source to share


3 answers


This is probably confusing because he mixes the two styles const

together.

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

      

I'll reorder them because the best way to understand them is to read them backwards in my opinion.

Let's start with the return type:

const int*const -> int const* const

      

Reading it back, we get: a const

pointer to const int

.



Likewise, for a function parameter:

const int* const& -> int const* const&

      

Reading it back, we get: a link to a const

pointer to const int

.

The function is also marked as const

, which means that it is a member function that can be called, for example, when the reference to this class is constant.

For possible optimizations const

and further understanding, see the following answers:

+5


source


const

tells the compiler that something is being read or is read-only data (or both). This is its main job and it helps the compiler to warn you (via compilation errors) when you accidentally change something you don't want / shouldn't.

Additionally, label member functions const

(when they do not modify the object) allow them to be used in more contexts.



The optimizer can also use presence const

to help it optimize your code if it can prove that you are not really changing the thing const

. But because of such things as "aliasing", volatile

, mutable

and const_cast

(including C-style style) that exist in this language, in most cases it is fairly limited in its ability to do so.

+3


source


break it down:

const int*const Method3(const int*const&)const;
  ^         ^             ^          ^      ^  
  |         |             |          |      |
  |         |             |          |      |-> you can use it in objects declared as constants
  |         |             |          | 
  |         |             |          | ->  you get a const pointer to const int(the paramater can no be changed in any form)
  |         |              
  |         | ->  you get a const pointer to const int(the returned value can no be changed in any form)            

      

+2


source







All Articles