Skip to main content
GameDev.net gamedev.net
🔒 Locked

Very Simple Question

Started by Helicon56 Jun 13, 2002 at 12:22 PM 4 replies 150+ views
Original Post
Helicon56
Helicon56
Hi, This is just something that''s been bugging me lately, and is very basic. Temprorary objects that are declared within a function...whats the memory management for them? void SwapVector(Vector &vec1, Vector &vec2) { Vector temp; temp = vec1; vec1 = vec2; vec2 = temp; } What happens for temp? Does it get allocated and freed every function call, or does it get allocated once and reused ever function call....or what? Sorry about how basic this is, i just thought i really should know the answer to something like that. Thanks anyway.
ktuluorion
ktuluorion
The memory for the variable temp will be reallocated each time the function is called.
[Piebert Entertainment] [Ask The All-Knowing Oracle A Question]------------------------------------------------------------GDSFUBY GameDev Society For UnBanning YodaTheCodaIf you want to see yoda unbanned then put this in your sig ------------------------------------------------------------DAIAGA Dave Astle is a God Association. To join, put this in your sig!Founder and High Priest o
Abominacion
Abominacion
It will be allocated in the stack each time the function is called, don''t worry, it''s just a sub esp,4 or a push , there are no system calls involved.


------------------------------------------------------
Cuando miras al abismo el abismo te devuelve la mirada.
F. Nietzsche
thona
thona
Furthermore it is ONE call for ALL objects at once. Basially the size of all objects used is allocated on the stack.
RegardsThomas TomiczekTHONA Consulting Ltd.(Microsoft MVP C#/.NET)
uNiQue0815
uNiQue0815
yes... "allocated" in stack, all vars in one call, as everyone said before

if you WANT it to be a variable that is allocated ONCE and used for every function call (with the last value stored), you can declare it static :

..
static Vector temp;
..

after that it''s like a global variable, that''s only available in the function
Evil Bill
Evil Bill
However, the thing you need to watch is your constructors. Your default constructor for Vector will be called every time the function is called. To fix this use:

  
void SwapVector(Vector &vec1, Vector &vec2)
{
Vector temp(vec1); // Copy constructor (if its defined)

vec1 = vec2;
vec2 = temp;
}

or use a static variable. Actually, ive seen several occasions where a static variable was used for non-primitive types in low-level functions like this. But i can''t think where.

HTH, Steve

Steve
DirectX Programmer
Soon to be the new Bill Gates
Member of the Unban Mindwipe Society (UMWS)

Topic Locked

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

Sign in to reply to this topic.