+ 4
Pass by reference or pass by pointer?
We can pass a vector to a function to change its actual members by two ways: 1: void func(vector<int>*ptr) ... func(&vec); 2: void func(vector<int>& vec) ... func(vec); But what's the difference between the two? Which one shall I choose and which one is better/faster?
23 Answers
+ 4
@ani Jonas, I would like you to look at the output of this code and observe why the address of argument by pointer is different ... Possibly, you will have a reason to that.
https://code.sololearn.com/c94TKB57l42U/?ref=app
For this reason, I will say that pointers and reference are not doing the same thing... For huge classes, reference will definitely give better performance because new objects are not being created
References just access the location directly without having to store it in another location like pointers.
+ 4
Both passing a pointer and passing a reference allow you to modify the contents of a vector in a function, but they have some differences in terms of syntax and behavior.
When you pass a pointer to a function, you are passing the memory address of the vector, and the function can modify the vector through this address. This requires the use of the dereferencing operator "*" to access the vector elements. For example, if you want to access the first element of the vector, you would use (*ptr)[0]. This can be less intuitive and more error-prone, especially for beginners.
When you pass a reference to a function, you are essentially passing an alias of the vector, and the function can modify the vector directly using normal dot notation. For example, if you want to access the first element of the vector, you would use vec[0]. This syntax is usually considered more natural and less error-prone.
In terms of performance, passing a reference is usually faster than passing a pointer because there is no need to dereference the pointer. However, the performance difference is usually negligible for small vectors.
In general, if you are not dealing with legacy code or special cases, it is recommended to pass a reference to modify the contents of a vector in a function, as it is more intuitive and less error-prone.
+ 4
G.Terang well explained 💯
Ali_combination I will recommend a book that specifically talk in details about your question...
The title is "C++ primer" rewritten for c++ 11... You can find it on Amazon.
It says and I copied from page 280 :.......
"It can be inefficient to copy objects of large class types or large containers by passing through pointers. Moreover, some class types including IO types cannot be copied. Function must use reference parameters to operate on objects of a type that cannot be copied or is of large containers.
Another instances of using reference is that some function can return only a single value. However, sometimes a function has more than one value to return. Reference parameters let us effectively return multiple results....""
This book is interesting... There's a lot to learn from it
+ 3
To answer your first question, the difference between passing by reference and passing by pointer isn't so obvious.
I would say that pointers are objects i.e they have a location address in memory that hold the address of another object. However a reference is not an object... A reference is just a nickname for an object that is existing.
In your example, the first function that uses int* ptr will create like a local variable then copy the value of the argument passed to it when called... You can imagine it as something like this
// Outside the function
int* mainPTR = &obj;
// Inside the function
int* ptr = mainPTR;
So technically, you're just creating a local variable of int* ptr in the first example
However, the second example does not create any variable, it just give a nickname to the existing variable it's a reference
Now without a doubt, it's obvious references are better and will be faster. Imagine having to create a local instance for heavy classes
+ 3
Ali_combination
I like this phrase:
"In C++ use references when you can, and pointers when you have to."
The replies pretty much have everything covered. But if you're up to reading more about pointers vs reference:
https://www.geeksforgeeks.org/pointers-vs-references-cpp/amp/
+ 2
ıllıllı ѕнαικн нαмzα ıllıllı i agree on it 👍
+ 2
references are pointer is false. References are aliases and cannot be a pointer. The compiler code for reference may differs too and the standard treats them differently.
Some compilers will and mostly not reserve space for references in the stack and the referenced object will be replaced by them but that's not the case for pointers.
It's normal to use any of those for simple codes that's been provided in this thread but for complex programs, the compiler knows without any analysis that references cannot be reseated or have it address taken.
References only exists in the source code and they are constants to their referenced object... They can do pretty much what the pointer does but they are not pointers.. they don't point, you can't dereference or increment or do stuff.
my understanding about it is that references is that object itself, pointer is another object that knows about the referenced object
+ 2
Pass by reference: This is a way of calling function in which we pass in function arguments values .
* Another thing is that it's used when we don't want to change in global variables only function perform with local variables.
Pass by pointer : In this , as a function argument, we pass the addresses of global variables .
* In this, we need to change our global variables so we pass global variables addresses .
As an example, we created a function for swap two no function, and then we need to Pass it's global variables addresses, not variables reference (values ) otherwise in function local variables will be swap but when we print it in main then it's normal as like before 😏
+ 2
I will also like to mention that the book emphazises(pardon my spelling there lol) on references not being a pointer..and infact references aren't pointers under the hood ... They are just so different
+ 1
Ani Jona 🕊 I see ok.
+ 1
Mirielle great 👍 thank you.
+ 1
ıllıllı ѕнαικн нαмzα ıllıllı you seems to be a big fan of gpt... I'd like you to read this thread concerning that
https://www.sololearn.com/Discuss/3021159/?ref=app
+ 1
Ani Jona 🕊 thank you also for sharing the book (Optimization software in C++). It may be a good book to read.
+ 1
Ani Jona 🕊 I'm not much familiar with assembly and how C/C++ work, are pointers saved in CPU registry ? (and not stack or heap ?)
+ 1
Ani Jona 🕊 ok, im asking because i couldn't exactly understand what you were saying up there in your last comment.
+ 1
Okay friends, I see different responses and I may need to pump up my knowledge if I want to understand them well. Thank you very much for taking the time to help me out.
+ 1
Salam Aleykum bratvalar
+ 1
emil q-yevv Hello Emil. Please read rules of Sololearn forum. Getting away from the main topic is not the right thing to do, stick to it please. 👍
+ 1
you don't "fetch" object using reference
A reference is that object itself !
That's the point
a pointer is another object that knows the object
Ani Jona 🕊 a ref is that object itself... it easier and faster for me(ref) to take stuff in my house than asking a friend(ptr) who's got my address to do it on my behalf
+ 1
It's also worth summarizing that the Google Benchmark result shows that ref is faster... And there would be huge difference when working with large objects.
"Copying by passing through pointers" is actually preceded with an example of how pointers do create local variables then copy the address values inside it and other related stuff.. as shown in the code I provided yesterday
Also I clearly stated yesterday that the difference between both isn't that obvious but it doesn't mean they're doing the same thing... They're not
Copying large objects is involved because OP is using std::vector, which likely may have the size 9e10 with strings of atmost 1000 characters.. this is def a large data and reference will perform far better than pointers in this case
In conclusion (cos I will unfollow the discussion)... Ref is not an object and is faster than pointers. A ref is the object itself and in most cases used to avoid copying or creating new variables as ptr would.