|
|
but we saved the newplayer to player pointer |
Player newplayer;
player = &newplayer
newplayer
has been destructed and the memory location 0x40003000 is available for reuse.10.6 Three kinds of memory management So far, we have seen two distinct kinds of memory management, although we have not discussed them explicitly. The first kind is usually called automatic memory management, and is associated with local variables: A local variable occupies memory that the system allocates when it encounters the variable's definition during execution. The system automatically deallocates that memory at the end of the block that contains the definition. Once a variable has been deallocated, any pointers to it become invalid. It is the programmer's responsibility to avoid using such invalid pointers. For example,
This function returns the address of the local variable x. Unfortunately, when the function returns, doing so ends execution of the block that contains the definition of x, which deallocates x. The pointer that &x created is now invalid, but the function tries to return it anyway. What happens at this point is anybody's guess. In particular, C++ implementations are not required to diagnose the error—you get what you get. If we want to return the address of a variable such as x, one way to do so is to use the other kind of memory management, by asking for x to be statically allocated:
By saying that x is static, we are saying that we want to allocate it once, and only once, at some point before the first time that pointer_to_static is ever called, and that we do not want to deallocate it as long as our program runs. There is nothing wrong with returning the address of a static variable; the pointer will be valid as long as the program runs, and it will be irrelevant afterward. However, static allocation has the potential disadvantage that every call to pointer_to_static will return a pointer to the same object! Suppose we want to define a function such that each time we call it, we get a pointer to a brand new object, which stays around until we decide that we no longer want it. To do so, we use dynamic allocation, which we request by using the new and delete keywords. |
but in visual studio when i try to go address of newplayer object it gives me health as result even its out of scope ? |
At the end of the function, the Player object is destroyed. It was in memory location 0x40003000. Now, that memory can be reused and something else put there. |