Can heap variables have an identifier?

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 = new int;
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).
Last edited on
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 = new int;
    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.
Last edited on
Hello anarelle,

I have never really tried this, but I believe you could typedef the "pnt" to a different name.

While declaring any stack variables like int* pnt associates the pnt identifier to the variable.


Whether it is stored on the stack or the heap "pnt" is still the variable name.

Andy
Topic archived. No new replies allowed.