Recently while I was explaining the basic difference between pointers and references(in context of C++ programming) to someone, I told the usual explanations which talk about different function argument passing conventions - Call by value, Call by pointer, Call by reference, and all the associated theory about references.
But then I thought whatever a C+ reference does in terms of argument passing,(Allows a memory efficient way of passing large structures/objects, at same time keeps it safe by not allowing the callee to modify any variables of the object passed as reference, if our design demands it)
A const pointer in C would achieve the same thing , e.g. If one needs to pass a structure pointer say struct mystr *ptr, by casting the structure pointer as constant -
func(int,int,(const struct mystr*)(ptr));
will ptr not be some kind of equivalent to a reference?
Will it not work in the way which would be memory efficient by not replicating the structure(pass by pointer) but also be safe by disallowing any changes to the structure fields owing to the fact that it is passed as a const pointer.
In C++ object context, we may pass const object pointer instead of object reference as achieve same functionality)
If yes, then what use-case scenario in C++, needs references. Any specific benefits of references, and associated drawbacks?
thank you.
-AD
No, it doesn't. It has pointers, but they're not quite the same thing. For more details about the differences between pointers and references, see this SO question.
What is a reference variable in C++? C++ProgrammingServer Side Programming. Reference variable is an alternate name of already existing variable. It cannot be changed to refer another variable and should be initialized at the time of declaration and cannot be NULL. The operator '&' is used to declare reference variable ...
The official C++ "documentation" is the C++ standard, ISO/IEC 14882:2014(E).
Yes - C++ can use C libraries.
You can bind a const reference to an rvalue:
void foo(const std::string& s);
foo(std::string("hello"));
But it is impossible to pass the address of an rvalue:
void bar(const std::string* s);
bar(&std::string("hello")); // error: & operator requires lvalue
References were introduced into the language to support operator overloading. You want to be able to say a - b
, not &a - &b
. (Note that the latter already has a meaning: pointer subtraction.)
References primarily support pass by reference, pointers primarily support reference semantics. Yes I know, the distinction isn't always quite clear in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With