Strange type in C ++

I have a method with a prototype:

bool getAssignment(const Query& query, Assignment *&result); 

I am a little confused about the type of the second parameter ( Assignment *&result ), since I do not think I have seen anything like this before. It is used as:

  Assignment *a; if (!getAssignment(query, a)) return false; 

Is this a link to a pointer or vice versa? or not? Any explanation is appreciated. Thanks.

+8
c ++ reference types parameters
source share
2 answers

This is a link to a pointer. The idea is to be able to change the pointer. It is like any other type.


Detailed explanation and example:

 void f( char* p ) { p = new char[ 100 ]; } int main() { char* p_main = NULL; f( p_main ); return 0; } 

will not change p_main to point to the allocated char array (this is a specific memory leak). This is due to the fact that the pointer copies the pointer, it is passed by value (it is like passing the value of int by value, for example void f( int x ) ! = void f( int& x ) ).

So if you change f :

 void f( char*& p ) 

now it will be p_main by reference and will change it. So this is not a memory leak, and after f , p_main will correctly indicate the allocated memory.


PS The same can be done using a double pointer (for example, C has no links):

 void f( char** p ) { *p = new char[ 100 ]; } int main() { char* p_main = NULL; f( &p_main ); return 0; } 
+18
source share

For something like this, you basically read the declaration from right to left (or inside out).

In other words, you want to start with the name of the item being declared, and then move forward. In this case, passing directly from the name to the type, we get:

enter image description here

+12
source share

All Articles