1

If reference in C++ is just an alias to an existing variable, why does it have same size as pointer? If they are implemented like pointers only then why creating a separate topic?

struct a{
           int x;
           int &y=x;
};

In this scenario sizeof(a) turns out to be 8 which tries to say that y is taking extra memory for itself.

Which of them is actually fast or both of them consume same time? Which of these concepts is then moved to Java and is closely related to references in Java?

  • @BiagioFesta I have studied the complete thread which you are referring but answers in that thread contradict to each other and thats why I have doubts.If reference shares address with original variable, then why does it contribute in size. If it is similar to pointer how come it creates different topics like pass by pointer vs pass by reference. – Sanjeet Kumar May 20 '18 at 09:03
  • To quickly answer your four questions: 1) compilers implement references using pointers; 2) implementation dependent, the standard does not require that; 3) you'd need to profile your optimized code on your platform; 4) Java references are very different from C++ references. – Eljay May 20 '18 at 12:57
  • @Eljay Thanks for the to the point reply. Now this is what I somewhat agree with. But you left me puzzled in one question. How exactly are Java references implemented. I can't just ask this question as someone will just mark it dilate without going in details. – Sanjeet Kumar May 24 '18 at 08:00
  • In Java, all objects are accessed by reference. (Java distinguishes objects from primitives.) The closest equivalent in C++ would be if **all** objects (but not "primitives") were accessed through `std::shared_ptr` -- that'd be pretty extreme style of programming in C++. Java uses garbage collection, and shared_ptr is reference counted, but that's a minor detail. – Eljay May 24 '18 at 13:05
  • Thanks @Eljay. That's enough for a head start. I will know go in depth for the topic and will see if there is something worth asking or sharing. – Sanjeet Kumar May 26 '18 at 02:24

0 Answers0