Skip to main content
gamedev.net
🔒 Locked

memory allocation query

Started by makingroulette Jun 18, 2005 at 7:31 AM 3 replies 1k views
Original Post
makingroulette
makingroulette
How do you create instances of an object dynamically on the stack? can you give an a code example
darookie
darookie
Well I don't know what you mean by "dynamically on the stack", since you usually create objects dynamically on the heap. I assume you use C++.
You can, however, use the placement new operator to create objects dynamically on stack memory. Please note that this is dangerous and should be used with care (e.g. use it only when you know what you are doing!).

#include <new>// some memory block allocated on the stackchar globalMemoryOnStack[GLOBAL_MEMORY_SIZE];// some class - I left out declaration and definition.class A;void SomeFunc() {   // use placement-new to allocate an object of type "A" dynamically on the stack   A * a = new(globalMemoryOnStack) A;   // use A and don't call "delete" on it! call the destructor explicitly instead:   (*a).~A();}


HTH,
Pat.

PS: And be careful, there're only a few valid instances where you actually want to use this method.
nmi
nmi
You can use alloca to allocate the memory on the stack, then do as darookie suggested:

A * a = new(alloca(sizeof(A))) A;...(*a).~A();


(If your compiler does not support alloca, you can easily write one by yourself.)
makingroulette
makingroulette
I asked the question because I was reading a book called Microsoft Visual C++ .NET Step By Step page 132 The .NET approach to controlling object lifetimes

Heres the extract that is puzzling me, the sentence starting with 'Unmanaged'


Using the .NET mechanism, you still create objects dynamically using the new operator, but the system is responsible for deleting objects, not you. The system keeps track of references to objects, and when an object is no longer being referenced by anyone, it becomes a candidate for garbage collection.

This has more consequences for the programmer than you might at first think:

Objects are always created using new. Unmanaged code lets you create objects on the heap (as automatic variables) or dynamically on the stack. For garbage collection to work, objects have to be accessed through some sort of reference, which in C++ is a pointer.



Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.