简体   繁体   中英

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?

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()

The new operator returns a pointer to whatever it's allocated for you. When you dereference a pointer, you get a reference to the value it points to. Simple as that.

It's been that way since C (though references weren't an explicit thing). It allows code like this:

void modify_my_int(int* the_int) { *the_int = 4; }

int main(void)
{
    int var;
    modify_my_int(&var);
    printf("%d\n", var); // prints "4"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM