Passing a pointer by reference in C ++

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

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

However, I heard that this is a bad form and can cause problems. Here is a method that my colleague suggested using:

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

It seems to me that they both do the same. Is there a difference between the compiler between the two methods (I am using Visual Studio 2005)? What is right?

+6
source share
2 answers

I do not think there is a difference between the two. You should ask your colleague why he thinks there is.

What could be for convenience of service, where if you want to switch from unsigned char * to char * , you only need to change one place. But this, I think, can lead to other problems.

+7
source

Is there a difference between the compiler between the two methods (I am using Visual Studio 2005)?

As others have rightly pointed out, no.

What is right?

Between the two alternatives, it boils down to the debate "I have to hide pointers behind typedefs." There are valid arguments for any position.

However, I think that both pieces of code suffer from over-specialization. I prefer to code algorithms as template functions, so I don’t repeat it myself .

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

 template <class InputIterator> bool myFunction(InputIterator &iter) { std::cout << *iter; ++iter; return true; } 
+5
source

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


All Articles