Search code examples
c++pointersmemorynew-operatordelete-operator

Does a pointer take up memory before assignment?


Say I have this:

int *thing;

Is that using 4 bytes of memory even though I have nothing assigned to it? And when I assign something (thing=new int;), would it then use 8 bytes because the pointer itself might use memory?

Also, say I had this:

struct thingy
{
    int *intThing;
}

thingy *result=new thingy;
thingy.intThing=new int;
delete thingy;

Would intThing be deleted as well, or would the memory be left floating around with nothing pointing to it?


Solution

  • All variables (primitive numeric types, class instances, pointers, references) start out taking up space.

    Then the optimizer gets involved, and may show that some storage is redundant (the value is constant, or always available from another variable, etc)

    Making variables disappear is one of the explicit goals of the optimizer because it tends to reduce register pressure, improve cache performance, etc.

    In your example, the pointer intThing would be destroyed (it's a member and members die when their parent object does), but the memory it points to (which would correctly be called *thingy.intThing and not just thingy.intThing) will not. If its address is not stored anywhere else, then it would be leaked.