Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Reference to dynamic memory

All considerations about when to use which aside, I am still unsure about pointer vs reference semantics.

Right now, I am under the impression that references are essentially pointers that must be initialized when they are declared, and then from that point on cannot point to anything else. In other words, they are a like a Type* const (not Type const*), or, they cannot be reseated. It essentially becomes a "new name" for that object. Now I heard that references do not actually need to be implemented by the compiler using pointers, but I am under the impression that you can still think of them this way, in regards to what their visible behavior will be.

But why can't you do something like this:

int& foo = new int;

I want to create a reference to dynamic memory. This does not compile. I get the error

error: invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'

That makes sense to me. It seems the new operator returns a pointer of given type to the address of memory that the OS? dynamically allocated for me.

So how do I create a "reference" to dynamic memory?

Edit: Links to resources that precisely explain the difference between references and pointers in C++ would be appreciated.

like image 798
newprogrammer Avatar asked Apr 05 '12 06:04

newprogrammer


People also ask

Does C support dynamic memory allocation?

Dynamic allocation is not supported by C variables; there is no storage class “dynamic”, and there can never be a C variable whose value is stored in dynamically allocated space.

What is dynamic memory in C language?

The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib. h header file.

Can memory be dynamically allocated for references?

Passing Dynamically Allocated Memory as Return Value by Reference. Instead, you need to dynamically allocate a variable for the return value, and return it by reference.

Where is dynamic memory in C?

This is known as dynamic memory allocation in C programming. To allocate memory dynamically, library functions are malloc() , calloc() , realloc() and free() are used. These functions are defined in the <stdlib. h> header file.


1 Answers

new returns a pointer to the allocated memory, So you need to capture the return value in a pointer.

You can create a reference to a pointer after allocation is done.

int *ptr = new int;
int* &ref = ptr;

then delete it after use as:

delete ref;

or more simply,

int &ref = *(new int);

delete it after use as:

delete &ref;
like image 165
Alok Save Avatar answered Oct 08 '22 20:10

Alok Save