logo

Crowdly

Browser

Add to Chrome

In C, we can have only a single name to specify an object. For example, the de...

✅ The verified answer to this question is available below. Our community-reviewed solutions help you understand the material better.

In C, we can have only a single name to specify an object. For example, the definition 

int n;

associates name n with a block of memory of size bytes. In C++, the concept of references allows us to associate multiple names to an object. For example, the first line of the following code fragment

int i{10};

int *pi{&i};

int &ri{i};

ri = 21;

std::cout << i << ' ' << ri << ' ' << *pi << '\n';

associates name i to an int object. Such a named object is called a variable. The second line defines a pointer variable pi and initializes it with the address of variable i. We can directly refer to the object using name i or indirectly refer to the object using expression *pi. The third definition introduces name ri as a reference to variable i. C++ uses the term reference to mean that name ri is an alias to name i: anywhere you can use name i, you can now use alias ri. That is, the object associated with named i has a second name ri associated with it. Therefore, the code fragment will write  thrice to the standard output stream.

Although it seems that references are similar to pointers, they differ in several essential ways:

  • Pointers can be uninitialized, while references must be initialized [because they must be an alias of something].
  • Once a reference is initialized to alias an object, it cannot be made to alias a different object. On the other hand, pointers can be reassigned to point to another object.
  • There is no such thing as a null reference while we can have a null pointer [by initializing or assigning value nullptr to a pointer variable].

Although every reference must be initialized to refer to something, it is still possible to have a dangling reference. Dangling references arise when a reference is initialized to alias a dynamically allocated object which is then subsequently deleted. Consider the following code fragment:

int *pi = static_cast<int*>(malloc(sizeof(int)));

*pi = 10;

int &ri {*pi}; // ri is now an alias to unnamed object pointed to by pi

ri += 1; // update to 11 the value of object pointed to by pi

free(pi); // the object that pi is pointing to is no longer in existence!!!

// note that the physical memory still exists but not

// the dynamic object that was earlier given storage there

// therefore, ri is now a dangling reference

ri += 2; // undefined behavior

Which of the following code fragments do NOT compile?

0%
0%
More questions like this

Want instant access to all verified answers on distance3.sg.digipen.edu?

Get Unlimited Answers To Exam Questions - Install Crowdly Extension Now!

Browser

Add to Chrome