Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a pointer by reference in c++

I have a function where I'm passing in an iterator to a char * buffer (which is also a char *). The function needs to increment the iterator. Anyway, I found that a good method of passsing the iterator into the function is by passing the pointer by reference:

bool myFunction(unsigned char * &iter)
{
   ...

However, I've heard that this is bad form and could cause problems. Here is the method that my coworker suggested I use:

typedef unsigned char * unsignedcharptr;
bool myFunction(unsignedcharptr &iter)
{
   ...

It looks to me like they're both doing the same thing. Is there a compiler difference between these two methods (I'm using Visual Studio 2005)? Which is correct?

like image 330
Joe Lyga Avatar asked Feb 10 '12 16:02

Joe Lyga


2 Answers

I don't think there's any difference between the two. You should ask your coworker why he believes there is.

What might be the cause is for maintainability, where if you wanted to switch from unsigned char * to char * you'd only have to change one place. But this, I think, could lead to other problems.

like image 154
Luchian Grigore Avatar answered Sep 20 '22 00:09

Luchian Grigore


Is there a compiler difference between these two methods (I'm using Visual Studio 2005)?

As others have correctly noted, "no".

Which is correct?

Between the two alternatives, it entirely comes down to the "should I hide pointers behind typedefs" debate. There are valid arguments for either position

However, I think that both of your code snippets suffer from over-specialization. I prefer to code algorithms as template functions so that I Don't Repeat Myself.

If your design supports it, you could generalize your code to accept any iterator:

template <class InputIterator>
bool myFunction(InputIterator &iter)
{
  std::cout << *iter;
  ++iter;
  return true;
}
like image 24
Robᵩ Avatar answered Sep 20 '22 00:09

Robᵩ