johnbakers
johnbakers

Reputation: 24750

Are non-pointer instance variables stored on the heap?

The difference between stack and heap is well documented when in the context of a local function, but I'm curious about instance variables.

Since an instance variable needs to stick around until it is released, is it stored in the same type of memory regardless of whether it is created with new or not?

i.e.

Class A{
  SomeType s1;
  SomeType * s2;
 }

If these were automatic local variables, the difference between these two mechanisms is considerable. But as instance variables, they are more or less in the same place in memory, both on the heap?

Upvotes: 3

Views: 728

Answers (2)

Alok Save
Alok Save

Reputation: 206528

Non pointer variables are defined in storage areas depending on how or where they are declared.

Myclass obj;

at function scope will be created on automatic storage while if created at global scope will be created with static storage duration.

In your example, both A::s1 and A::s2 will have the same storage area as the object to which they belong. However, since A::s2 is a pointer it might point to a object which might be placed in different storage area.

For example:

void doSomething()
{    
    A obj;
    SomeType obj2;
    obj.s2 = &obj2;
}

A::s2 points to a object whose storage is same as obj, while:

void doSomething()
{
    A obj;
    SomeType *ptr = new SomeType;
    obj.s2 = ptr;
}

A::s2 points to a object which is dynamically allocated.

Note: Above code assumes A::s2 to be public for sake of simplicity.

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249153

A::s1 and A::s2 will be, by definition, stored in whatever way and place that an instance of A is created. As for the location of the storage pointed to by A::s2, it could be anywhere.

Upvotes: 5

Related Questions