Thursday, June 27, 2019

c++ - How is a reference different from a pointer in implementation?











I am reading about the book "Inside the C++ Object Model" by Stanley Lippman. What puzzles me is the difference between a "reference" of an object and a "pointer" to an object. I know that a reference must be initialized when declared, while a pointer could be left for later initialization. But I want to know the physical implementation difference between them.



Why should there be the "reference" mechanism; isn't it overlapping the function of a pointer? Under what circumstance should we use reference other than pointer? Many thanks.


Answer



Most references are implemented using a pointer variable i.e. a reference usually takes up one word of memory. However, a reference that is used purely locally can - and often is - eliminated by the optimizer. For example:



  struct S { int a, int b[100]; };  
void do_something(const vector& v)
{

for (int i=0; i int*& p = v[i].b;
for (int j=0; j<100; ++j) cout < }


In this case, p needs not be stored in memory (maybe it just exists in a register, maybe it disappears into the instructions).


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...