class members, stack or heap?

Started by
10 comments, last by MarkusPfundstein 12 years ago

int main() {
int x = new int;
//Use the variable
delete x; //Deallocate now that your done
return 0;
}
I just feel the need to point out this is strongly discouraged. Modern C++ is not so easy. Use [font=courier new,courier,monospace]auto_ptr [/font]or everything else ensuring proper release in case of exception. There's no guarantee, in general, the code will reach the [font=courier new,courier,monospace]delete [/font]call. It's also worth noticing OP forgot a pointer declaration: the above code won't compile, but I take for granted that was just a typo.

Previously "Krohm"

Advertisement
Hey, the answer to your question is fairly easy, just think about how the memory is layed out. When you have a class point and it has two member variables x and y like this:

class point {
public:
float x_;
float y_;
};

than the memory footprint is 8 byte on a 32 bit system. 2*float.

Stack:

int main()
{
point p;
int x = p.x_;
}

First, the stack pointer decrements by 8 byte (sizeof(point)) . When you refer than to x_, the assembly just takes the baseadress of p, inrements it by the offset 8 and puts that address in a register to be able to do the assigment to local x. Than it will decrement back to the old position and do the assignment.

Heap:

int main
{
point *p = new point;

int x = p->x_;

delete p;
}

What happens here is, that in the first line, the compiler will increment the stack pointer by 4 byte (1 * sizeof(point*)). Than new will find us a free address in the heap space (higher memory address space than the stack) will flag it as taken and return the address which gets stored in the 4 bytes from *p.

When we access this thingy now, assembly will look whats written in *p .This process is dereferencing. If there is a valid value it will jump to the memory address which is stored there, will increment by 8 and put the value there in a register. It will than jump back and assign it to x. :-) We could discuss now if heap access is slower than stack access :-)

If there is anything wrong or incorrect i would appreciate it if people could explain better :-)

Note: It will be different when there is a vtable :-)

I open sourced my C++/iOS OpenGL 2D RPG engine :-)



See my blog: (Tutorials and GameDev)


[size=2]http://howtomakeitin....wordpress.com/

This topic is closed to new replies.

Advertisement