Const with output pointers

I have this piece of C ++ code that I got a little confused:

int foo (const char* &bar) 

In this case, if I want to write a pointer to the panel as:

 bar = ... 

This is normal. So how should I understand this const . How does a const pointer other than a pointer point to a const value?

+4
source share
3 answers

const is applied to what is to his left, if there is nothing to his left, in which case it refers to everything that is to his right. This means that in your case, bar is a reference to a pointer to const char . bar itself is not constant and can be changed.

If you change bar to char * const &bar , that is, a link to a constant pointer to char , you cannot complete this task. Example:

 int foo (char * const &bar) { bar = 0; return 1; } 

and trying to compile it:

 $ clang++ -c -o example.o example.cpp example.cpp:3:9: error: read-only variable is not assignable bar = 0; ~~~ ^ 1 error generated. make: *** [example.o] Error 1 

You can use cdecl / c++decl to parse these declarations if they cause you problems:

 $ c++decl Type `help' or `?' for help c++decl> explain const char * &bar declare bar as reference to pointer to const char c++decl> explain char * const &bar declare bar as reference to const pointer to char 
+4
source

If the pointer is const , you are not allowed to assign a pointer. For instance.

 char * const bar; bar = ...; // This is invalid *bar = ...; // This is OK bar[i] = ...; // This is OK 

If the pointer points to a const value, you are not allowed to assign what the pointer points to. For instance.

 const char *bar; bar = ...; // This is OK *bar = ...; // This is invalid bar[i] = ...; // This is invalid 
+4
source

I will give some examples. Maybe this will make some people easier:

Spaces have no meaning in any of them, so I put them everywhere to avoid ambiguity.


 const char * & bar 

bar not const, *bar is const (this also means bar[0] , etc.). If you change bar , it will now point to new memory (for example, a new array), but the old data will remain unchanged.


 char const * & bar 

as stated above.


 char * const & bar 

bar now const (you cannot change it to point to another memory), but the memory itself ( *bar ) can be changed


 const char * const & bar 

bar and *bar are constants. You cannot change anything.


 char * & const bar 

This is mistake.


The code you found uses the first form (in fact) to return a const char array. The caller is not allowed to pass char* ; it must be const char* , so if the caller does not discard constness (which is bad), they will not change the memory. This means that the function can safely return a pointer to internal data, knowing that it will not be changed.

+2
source

Source: https://habr.com/ru/post/1499851/


All Articles