Memory allocation using reference variable in C ++

I compiled the following code snippet in the g ++ compiler , it works fine without any errors or warnings.

#include <iostream>             
int main()                      
{                               
    int &r = *(new int(100));   
    std::cout << r << std::endl;
    return 0;                   
}

How does a reference variable work with memory allocation?

Is memory allocation correct for a reference variable?

+4
source share
2 answers

From the C ++ standard (5.3.1 Unary operators)

1 * : , , lvalue, , . " T", - "T". [: ( cv void). lval ( , ); prvalue, . 4.1. -end note]

int &r = *(new int(100));

​​ lvalue, * , .

,

delete &r;

.

#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;
}

B::~B()
A::~A()
+5

new , . , , . .

C ( ). :

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"
}
0

Source: https://habr.com/ru/post/1677665/


All Articles