Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reference & const pointers in C/C++

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?

  1. 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)

  2. If yes, then what use-case scenario in C++, needs references. Any specific benefits of references, and associated drawbacks?

thank you.

-AD

like image 236
goldenmean Avatar asked Nov 20 '10 23:11

goldenmean


People also ask

Does C have reference?

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 reference variable in C?

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 ...

What is the official C++ reference?

The official C++ "documentation" is the C++ standard, ISO/IEC 14882:2014(E).

Can C++ use C libraries?

Yes - C++ can use C libraries.


1 Answers

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++.

like image 176
fredoverflow Avatar answered Oct 27 '22 00:10

fredoverflow