I have compiled following piece of code in G++ compiler, it's working fine without any error or warning.
#include <iostream>
int main()
{
int &r = *(new int(100));
std::cout << r << std::endl;
return 0;
}
How does the reference variable working with memory allocation?
Is it valid to allocate memory for reference variable?
Memory is allocated when a pointer is defined. A reference however, is a name alias & hence no memory is allocated for it( Is it correct? ). 2. Reference is bound to be initialized at the time of definition because, a reference is implemented with a constant pointer & hence cannot be made to point to the other object.
Reference Type variables are stored in a different area of memory called the heap. This means that when a reference type variable is no longer used, it can be marked for garbage collection. Examples of reference types are Classes, Objects, Arrays, Indexers, Interfaces etc.
What is a reference variable in C++? 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.
From the C++ Standard (5.3.1 Unary operators)
1 The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. If the type of the expression is “pointer to T”, the type of the result is “T”. [ Note: Indirection through a pointer to an incomplete type (other than cv void) is valid. The lvalue thus obtained can be used in limited ways (to initialize a reference, for example); this lvalue must not be converted to a prvalue, see 4.1. —end note ]
In this statement
int &r = *(new int(100));
there is declared a reference to the lvalue obtained by using the operator *
of an unnamed object created in the heap.
Lately you can delete the object using the reference
delete &r;
Consider a more interesting example with the polymorphism.
#include <iostream>
int main()
{
struct A
{
virtual ~A()
{
std::wcout << "A::~A()" << std::endl;
}
};
struct B : A
{
~B()
{
std::wcout << "B::~B()" << std::endl;
}
};
A &ra = *(new B);
delete &ra;
}
The program output is
B::~B()
A::~A()
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