Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange type in c++

I have a method with the prototype:

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

I am a bit confused about the type of the second param (Assignment *&result) since I don't think I have seen something like that before. It is used like:

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

Is it a reference to a pointer or the other way around ? or neither ? Any explanation is appreciated. Thanks.

like image 203
Cemre Mengü Avatar asked Jul 07 '12 15:07

Cemre Mengü


1 Answers

It's a reference to a pointer. The idea is to be able to change the pointer. It's 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 (it's a definite memory leak). This is because you copy the pointer, it's passed by value (it's like passing an int by value; for example void f( int x ) != void f( int& x ) ) .

So, if you change f:

void f( char*& p )

now, this will pass p_main by reference and will change it. Thus, this is not a memory leak and after the execution of f, p_main will correctly point to the allocated memory.


P.S. The same can be done, by using double pointer (as, for example, C does not have references):

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

    return 0;
}
like image 102
Kiril Kirov Avatar answered Sep 17 '22 18:09

Kiril Kirov