I've always thought of variables stored in the heap as variables that can only be accessed (indirectly) through a pointer, and not having an idenfitier of their own. For example, when doing something like int* pnt = newint;
the heap memory location where this int is stored doesn't have an identifier of its own. It just has a memory address, which I stored in my pnt variable.
While declaring any stack variables like int* pnt associates the pnt identifier to the variable.
So I'm curious about heap variables: is there any situation where I can declare a "named" variable in the heap? (even if I still need a pointer to access it).
new will always return a pointer, but you could dereference the pointer and connect it to a reference identifier.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Example program
#include <iostream>
int main()
{
int* ptr = newint;
std::cout << (ptr) << '\n';
int& my_identifier = *ptr;
std::cout << (&my_identifier) << '\n';
std::cout << "Above addresses should match\n";
delete &my_identifier;
std::cout << "Memory has been cleaned up\n";
}
0x3e5eb20
0x3e5eb20
Above addresses should match
Memory has been cleaned up
Edit: I want to emphasize the importance of it being a reference. If it's not a reference, then you're simply copying the value on to the stack, and still have a memory leak + undefined behavior from deleting stack memory.