Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I pass "T* const&" type of pointer ?

I would pass T*& pointer, when I am intending to change the pointed value inside the function:

void foo(char *&p)
{
  p = (b == true)? new char[10] : 0;
}

But I am not able to get what is the use case for T* const& kind of pointer (since that pointer is not changeable)? I mean why should not I pass simply T* const ?

void foo(char* const &p);  // p is not changeable
void foo(char* const p);   // p is not changeable
like image 538
iammilind Avatar asked Dec 13 '22 11:12

iammilind


2 Answers

You would use a T* const & as a parameter if the value of the pointer object might be changed by something external to your function and you wanted to be able to observe changes to the value of the pointer object or if you wanted to store a reference or pointer to the pointer object for later reading.

A T* parameter (equivalent to T* const as a function parameter) just gives you a copy of the pointer object, a snapshot of its value when it was passed to your function.

void foo( char* const& ptr )
{
    char* p1 = ptr; // initial value
    global_fn();    // ptr might be changed
    char* p2 = ptr; // new value of ptr
}

vs

void foo2( char* ptr )
{
    char* p1 = ptr; // initial value
    global_fn();    // ptr can't be changed, it's local to this function
    char* p2 = ptr; // will be the same as p1
}

Technically, even the function itself might change the value of the pointer to which it is passed a reference.

E.g.

char* p;

std::ptrdiff_t foo( char* const& ptr )
{
    ++p;
    return p - ptr; // returns 0, would return 1 if the parameter was by value
}

int main()
{
    char test[] = "Hello, world!";
    p = test;
    foo( p );
}
like image 116
CB Bailey Avatar answered Jan 03 '23 23:01

CB Bailey


The difference is realistically nil. const references are used to prevent copying of expensive-to-copy or, in generic code, uncopyable types, but since pointers are trivial, it's negligible and you may as well take by value.

like image 30
Puppy Avatar answered Jan 03 '23 21:01

Puppy