Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation with reference variable in C++

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?

like image 260
msc Avatar asked May 22 '17 07:05

msc


People also ask

Is memory allocated for reference?

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.

How are reference variables stored in memory?

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

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.


1 Answers

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()
like image 133
Vlad from Moscow Avatar answered Sep 17 '22 01:09

Vlad from Moscow