0

Why is not a good idea to pass a pointer as reference in C++?

In my data structure class, the teacher said that you should not passed a pointer by reference, his not very sure about why, but in his experience, he said that sometimes you can get unexpected results. So, the teacher recommended to not pass a pointer by reference. If I'm going to do that, I want to know why a pointer shouldn't be passed as reference. Which one I should use and why? // Setter Void setVar(const int*&); Void setVar(const int*);

12th Mar 2019, 4:42 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
3 Answers
+ 6
IMO, the reason why is because 1. Passing a pointer by reference, means that any change introduced to the reference will be reflected in the original pointer. As such, you are introducing a risk of that happening - Changing the address in a pointer passed to a function isn't generally what you'd want to do *on purpose*. 2. (1) applies, except that you are doing const int*& - There is generally no reason to pass pointers by reference, if you don't wish to alter the address stored by the original pointer, and yet const prevents you from doing so. Instead of const int*&, why not make life easier by just doing const int* (or even just int* if the method is simple enough to easily make sure that the pointer doesn't change over the course of it being in the function?
12th Mar 2019, 5:00 AM
Fermi
Fermi - avatar
+ 1
Saw this post and was curious so I tested a little with passing pointers by reference. https://code.sololearn.com/cm150WPc6FGt/#cpp I could definitely see this messing something up. I dont display this, but if i tried to use that pointer after the change on the memory location things would start acting really weird. C++ is cool for how it lets you really do almost anything. Even if it means increment memory location values haha. Btw I did want to mention that passing a pointer by reference reminds me of pointer arithmetic. Thats a fun topic on its own
13th Mar 2019, 1:30 AM
Joshua Shaver
Joshua Shaver - avatar
0
So... Passing a pointer by reference makes your program vulnerable? Because maybe you can get the address memory and do something for that memory? For example, if I find a code, where it pass a pointer by reference, how can I explore that vulnerability? Well I hope I have understood 😅, thx
12th Mar 2019, 7:14 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar